Simple Inline Form Validator with Pure Javascript

Category: Form , Javascript | September 15, 2014
Author:Kunano
Views Total:5,298 views
Official Page:Go to website
Last Update:September 15, 2014
License:MIT

Preview:

Simple Inline Form Validator with Pure Javascript

Description:

An easy-to-use form validator which enables you to validate a set of form controls in vanilla JS.

More features:

  • Custom error messages.
  • Border and text feedback.
  • Custom validation rules.
  • Auto hide error messages.

Basic Usage:

Load the JS From Validator JS library into your document.

<script src="js-form-validator.js"></script>

Create a set of form controls and use data-rule attributes to specify the validation rules for each control.

<form name="demo-form">
  <input type="text" name="phone" data-rule="required|phone">
  <input type="checkbox" name="agree" id="agree" data-rule="required">
  <select name="city" data-rule="required" data-default="3">
    <option value="0">--No select--</option>
    <option value="1">New York</option>
    <option value="2">Amsterdam</option>
    <option value="3">Las Vegas</option>
    <option value="4">New Jersey</option>
  </select>
</form>

Enable the JS form validator with default settings.

(function () {
var init = function () {
//get form handle
var formHandle = document.querySelector('form[name="demo-form"]'),
//got to validation
validator = new Validator(formHandle, function (err, res) {
//return validation result
return res;
});
};

Available settings.

  • onAir: true: Validation of a current field after the events of “change”, “keyup”, “blur”
  • showErrors: true: Show validation errors
  • autoHideErrors: false: Auto-hide the error messages
  • autoHideErrorsTimeout: 2000: Timeout auto-hide error messages
  • locale: 'en': Language error messages
  • messages: {}: Object for custom error messages
  • rules: {}: Object for custom rules

Custom the styles of error messages in the CSS.

.error {
  ...
}

You Might Be Interested In:


Leave a Reply