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.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

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="******">
          <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;
}

            
          
!
            
              // Модуль DataValidator
// --------------------
var DataValidator = (function() {
  'use strict';

  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 DataValidator = function(data) {
    this.data = data.trim();
    this.length = this.data.length;
  };

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

  DataValidator.prototype.init = function(rules) {
    var results = { data: this.data, passed: [], failed: [] };

    for (var rule in rules) {
      var param = rules[rule];
      var config = { rule: rule, param: param };

      if (!this[rule](param)) { results.failed.push(config); }
      else { results.passed.push(config); }
    }

    results.valid = results.failed.length === 0;

    return results;
  };

  return DataValidator;
})();

// Модуль InputValidator
// ---------------------
var InputValidator = (function() {
  'use strict';

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

  var InputValidator = function(element, settings) {
    this.element = element;
    this.settings = settings;
  };

  InputValidator.prototype = Object.create(DataValidator.prototype);
  InputValidator.prototype.construnctor = DataValidator;

  InputValidator.prototype.validate = function() {
    DataValidator.call(this, this.element.value);
    var results = this.init(this.settings.rules);
    if (!results.valid) {
      var failed = results.failed[0];
      this.message = _createMessage(this.settings.messages[failed.rule], {
        data: results.data,
        rule: failed.param
      });
      this.settings.onError.call(this);
    } else {
      this.settings.onSuccess.call(this);
    }
  };

  return InputValidator;
})();

// Код для валидации
// -----------------
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 = 'Ура! Всё прошло хорошо, ваши данные полность валидные.';
};

DataValidator.prototype.password = function() {
  return this.data.toLowerCase() === '12345qwerty';
};

var emailInput = new InputValidator(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 InputValidator(document.getElementById('password'), {
  rules: {
    required: true,
    password: true
  },
  messages: {
    required: 'Это поле обязательно для заполнения!',
    password: 'Пароль должет быть 12345qwerty Значение "%data%" не подходит'
  },
  onError: onError,
  onSuccess: onSuccess
});

var validateBtn = document.getElementById('validate');
validateBtn.addEventListener('click', function(e) {
  emailInput.validate();
  passwordInput.validate();
}, false);

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console