cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

Quick-add: + add another resource

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <header class="container-fluid main-header">
    <div class="row">
      <h1>Валидация данных</h1>
    </div>
  </header>

  <!-- Классы в Bootsrap 3 - https://getbootstrap.com/css/#forms-control-validation -->
  <main class="container validator-container">
    <div class="row">

      <!-- Контейнер для email адреса -->
      <div class="col-sm-6">
        <div class="input-group center-block">
          <label for="email">Ваш адрес электронной почты</label>
          <input type="text" class="form-control" id="email" placeholder="example@email.com">
          <span id="email-error-container" class="help-block">Введите адресс вашей электронной почты</span>
        </div>
      </div>

      <!-- Контейнер для пароля -->
      <div class="col-sm-6">
        <div class="input-group center-block">
          <label for="password">Ваш пароль</label>
          <input type="password" class="form-control" id="password" placeholder="12345qwerty">
          <span id="password-error-container" class="help-block">Введите ваш пароль</span>
        </div>
      </div>

      <!-- Контейнер для кнопки, при нажатие на которую будет происходить валидация -->
      <div class="col-sm-12">
        <button class="btn btn-default" id="validate" type="button">Провести валидацию</button>
      </div>

    </div>
  </main>
            
          
!
            
              .main-header {
  background-color: #2c3e50;
  color: #ecf0f1;
  text-align: center;
  padding-bottom: 1.5rem;
}


.validator-container {
  margin-top: 2rem;
}

            
          
!
            
              var Validator = (function() {
  'use strict';

  var _createMessage = function(message, settings) {
    for (var key in settings) {
      message = message.replace('%' + key + '%', settings[key]);
    }
    return message;
  };

  // http://youmightnotneedjquery.com/#deep_extend
  var _extend = function(out) {
    out = out || {};

    for (var i = 1; i < arguments.length; i++) {
      var obj = arguments[i];

      if (!obj)
        continue;

      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (typeof obj[key] === 'object')
            out[key] = _extend(out[key], obj[key]);
          else
            out[key] = obj[key];
        }
      }
    }

    return out;
  };

  var regExps = {
    email: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
    url: /^((https?):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,
    numbers: /^\d+(\.\d{1,2})?$/,
    digits: /[0-9]*$/,
    letters: /[a-z][A-Z]*$/
  };

  var messages = {
    required: 'This field is required',
    min: 'This field should contain at least %rule% characters',
    max: 'This field should not contain more than %rule% characters',
    match: 'This field shold countain a valid %rule%'
  };

  var Validate = function(element, options) {
    var defaults = {
      regExps: regExps,
      messages: messages
    };

    this.options = _extend({}, defaults, options);
    this.element = element;
    this.regExps = regExps;
  };

  var fn = Validate.prototype;

  fn.validate = function() {
    var isValid = true;

    this.value = this.element.value.trim();
    this.length = this.value.length;

    for (var rule in this.options.rules) {
      var param = this.options.rules[rule];

      if (!this[rule](param)) {
        isValid = false;
        this.message = _createMessage(this.options.messages[rule], {rule: param, data: this.value});
        this.options.onError.call(this);
        break;
      }
    }

    if (isValid) {
      this.options.onSuccess.call(this);
    }
  };

  fn.required = function() { return this.length > 0;};
  fn.min = function(param) { return this.length >= param; };
  fn.max = function(param) { return this.length <= param; };
  fn.match = function(param) { return this.regExps[param].test(this.value); };

  return {
    init: Validate,
    fn: fn
  };
})();
var onError = function() {
  var parentNode = this.element.parentNode;
  parentNode.classList.add('has-error');
  parentNode.classList.remove('has-success');
  parentNode.querySelector('.help-block').textContent = 'Ошибка: ' + this.message;
};

var onSuccess = function() {
  var parentNode = this.element.parentNode;
  parentNode.classList.add('has-success');
  parentNode.classList.remove('has-error');
  parentNode.querySelector('.help-block').textContent = 'Ура! Всё прошло хорошо, ваши данные полность валидные.';
};

var emailInput = new Validator.init(document.getElementById('email'), {
  rules: {
    min: 5,
    max: 20,
    match: 'email'
  },
  messages: {
    min: 'Это поле должно содержать минимум %rule% символов. Значение %data% не подходит',
    max: 'Это поле должно содержать максимум %rule% символов. Значение %data% не подходит',
    match: 'Это поле должно содержать адрес электронной почты. Значение %data% не подходит'
  },
  onError: onError,
  onSuccess: onSuccess
});

var passwordInput = new Validator.init(document.getElementById('password'), {
  rules: {
    required: true,
    password: true
  },
  messages: {
    required: 'Это поле обязательно для заполнения!',
    password: 'Пароль должет быть 12345qwerty Значение "%data%" не подходит'
  },
  onError: onError,
  onSuccess: onSuccess
});
Validator.fn.password = function() {
  return this.value.toLowerCase() === '12345qwerty';
};
var validateBtn = document.getElementById('validate');
validateBtn.addEventListener('click', function(e) {
  emailInput.validate();
  passwordInput.validate();
}, false)

            
          
!
999px
Loading ..................

Console