Examples

OnError and onSuccess functions

These functions will be used as onError and onSuccess in every example.They are designed to work with Bootstrap classes:

var onError = function() {
  var parentNode = this.element.parentNode;
  parentNode.classList.add('has-error');
  parentNode.classList.remove('has-success');
  parentNode.querySelector('.help-block').textContent = 'Error: ' + 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 = 'Your data is valid';
};

Basic email validation example

Enter your email adress

Code for this validation

var emailInput = new Validator.init(document.getElementById('email'), {
  rules: {
    min: 5,
    max: 20,
    match: 'email'
  },
  onError: onError,
  onSuccess: onSuccess
});

var validateEmailBtn = document.getElementById('validate-email');
validateEmailBtn.addEventListener('click', function(e) {
  emailInput.validate();
}, false);
<div class="input-group center-block">
  <label for="email">Your email address:</label>
  <input type="text" class="form-control" id="email" placeholder="example@email.com">
  <span id="email-error-container" class="help-block">Enter your email adress</span>
  <button class="btn btn-default" id="validate-email">Validate email address</button>
</div>

Extend Validator function

To create your own validation methods just assign them to Validator.fn:

Validator.fn.password = function() {
  return /^(?=.*\d)(?=.*[a-zA-Z]).*$/.test(this.value); 
};

Advanced password validation

Enter your password

Code for this validation

Validator.fn.password = function() {
  return /^(?=.*\d)(?=.*[a-zA-Z]).*$/.test(this.value); 
};

var passwordInput = new Validator.init(document.getElementById('password'), {
  rules: {
    required: true,
    password: true,
    min: 8
  },
  messages: {
    password: 'Password should contain letters and numbers. %data% is invalid password'
  },
  onError: onError,
  onSuccess: onSuccess
});
var validatePasswordBtn = document.getElementById('validate-password');
validatePasswordBtn.addEventListener('click', function(e) {
  passwordInput.validate();
}, false);
<div class="input-group center-block">
  <label for="password">Your password:</label>
  <input type="text" class="form-control" id="password" placeholder="example@password.com">
  <span id="password-error-container" class="help-block">Enter your password</span>
  <button class="btn btn-default" id="validate-password">Validate password</button>
</div>