Powerful Multilingual Form Validation Plugin - jQuery Nice Validator

Powerful Multilingual Form Validation Plugin - jQuery Nice Validator
File Size: 228 KB
Views Total: 121
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Yet another jQuery-powered form validator used to validate form fields using custom validation rules.

Features:

  • Multiple languages (en, ja, zh-cn, zh-tw).
  • Custom rules using Regex or JS functions.
  • Supports both client-side and server-side validation.
  • Fully customizable and easy-to-extend.

Table Of Contents:

How to use it:

1. Download and load the Nice Validator plugin.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/dist/jquery.validator.min.js?local=en"></script>

2. Validate form fields using data-* attributes:

  • ; - AND
  • : - separate fields from rules
  • () - used to pass rule parameters
  • , - used to separate multiple rules
  • ~ - range
  • & - AND
  • ! - not equal to
  • | - OR
<form class="form" data-validator-option="{timely:2, focusCleanup:true}">
  <div class="form-item">
    <label class="label">Username</label>
    <input type="text" name="username"
      data-rule="required;username;"
      data-rule-username="[/^[\w\d]{3,12}$/, 'Please enter 3-12 digits, letters, underscores']"
      data-tip="You can use letters, numbers and periods"
    >
  </div>
  <div class="form-item">
    <label class="label">Password</label>
    <input type="password" name="pwd"
      data-rule="Password: required; length(8~16)"
      data-tip="Please fill in at least eight characters"
    >
  </div>
  <div class="form-item">
    <label class="label">Verify Password</label>
    <input type="password" name="pwdAgain" data-rule="Verify Password: required; match(pwd)">
  </div>
  <div class="form-item">
    <label class="label">Gender</label>
    <select name="gender" data-rule="required">
      <option value="">select ...</option>
      <option value="1">Male</option>
      <option value="2">Female</option>
      <option value="3">Other</option>
    </select>
  </div>
  <div class="form-item">
    <label class="label">Email</label>
    <input type="text" name="email" data-rule="required;email">
  </div>
  <div class="form-item">
    <label class="label">Interest</label>
    <label><input type="checkbox" name="interest" data-rule="checked">sports</label>
    <label><input type="checkbox" name="interest">movie</label>
    <label><input type="checkbox" name="interest">game</label>
  </div>
  <div class="form-item">
    <label class="label">Note</label>
    <textarea data-rule="required;"></textarea>
  </div>
  <div class="form-item">
    <label><input type="checkbox" id="agree_arguments" data-rule="checked">I agree to the service agreement.</label>
  </div>
  <div class="form-item">
    <button type="submit">Submit</button>
  </div>
</form>

3. Or via JavaScript.

$('#form').validator({
  fields: {
    'email': 'required;email',
    'pwd': 'required;length(6~16)',
    // ...
  }
});

4. Built-in validation rules:

  • required: required field
  • checked: checked(n), checked(n~), checked(~n), checked(n1~n2)
  • match: match(name), match(neq, name), match(lt, name), match(gt, name), match(lte, name), match(gte, name), match(gte, name, date), match(gte, name, datetime)
  • remote: remote(URL), remote(get:URL), remote(URL, name1, #id2 ...), remote(URL, foo=value1&bar=value2, name3 ...), remote(URL, foo:name1, bar:#id2, name3 ...), remote(jsonpURL), remote(jsonp:URL), remote(cors:post:URL)
  • integer: integer(+), integer(+0), integer(-), integer(-0)
  • range: range(n~), range(~n), range(n1~n2), range(n1~n2, false)
  • length: length(n), length(n~), length(~n), length(n1~n2), length(n~, true)
  • filter: filter(RegExp)

5. Create custom rules:

// en.js
$.validator.config({
  // Custom rules
  rules: {
    // ...
  },
});
// or
$("#form").validator(
  rules: {
    // ...
  }
);
// or via data attribute
<input name="demo" data-rule="required;xxx" data-rule-xxx="[/^\d{6}$/, '6 digits']">
// or via JS function
mobile: function(element, params) {
    return /^1[3458]\d{9}$/.test(element.value) || 'Phone Number Validator';
};

// using test function
loginName: function(element) {
  return /^[a-zA-Z]\w{3,}/.test(element.value) ||
    this.test(element, "mobile")===true ||
    this.test(element, "email")===true ||
    'Input username, phone number, or email';
}

// custom ajax validation
myRemote: function(element){
  return $.ajax({
    url: 'check/username.php',
    type: 'post',
    data: element.name +'='+ element.value,
    dataType: 'json'
  });
}

6. Available plugin options:

$("#form").validator(
  // 1 = enable debug
  // 2 = ignore validation result
  debug: 0,
  // 0: validate the form on submit
  // 1: validate the field when lose focus
  // 2: validate the field when the value has changed
  // 3: 1+2
  // 8: validate the field when the value has changed and show the result
  // 9: 1+2 and show the result
  timely: 1,
  // theme name
  theme: 'default',
  // ignore form fields
  ignore: '', 
  // ignore empty fields
  ignoreBlank: false,
  // move focus to the first invalid field
  focusInvalid: true,
  // clear error message when the field got focus
  focusCleanup: false,
  // stop the plugin when the first error is captured
  stopOnError: false,
  // default CSS classes
  formClass: 'n-default',
  validClass: 'n-valid',
  invalidClass: 'n-invalid',
  bindClassTo: null,
  // show success messages
  showOk: true,
  // custom error messages
  msgWrapper: 'span',
  msgArrow: '',
  msgIcon: '<span class="n-icon"></span>',
  msgClass: 'n-right',
  msgStyle: '',
  messages: {
    required: "Please fill in this field",
    email: "Please enter a valid email address.",
    // ...
  },
  msgMaker: function(opt) {
    var html;
    html = '<span role="alert" class="msg-wrap n-'+ opt.type + '">' + opt.arrow;
    if (opt.result) {
      $.each(opt.result, function(i, obj){
        html += '<span class="n-'+ obj.type +'">' + opt.icon + '<span class="n-msg">' + obj.msg + '</span></span>';
      });
    } else {
      html += opt.icon + '<span class="n-msg">' + opt.msg + '</span>';
    }
    html += '</span>';
    return html;
  },
  // custom display
  display: function(elem) {
    // ...
  },
  // function(elem) | jqSelector
  target: null,
  // apply options & validators to fields
  fileds: {
    // ...
  }
  // translate ajax response to validation result
  dataFilter: function (data) {
    if ( isString(data) || ( isObject(data) && ('error' in data || 'ok' in data) ) ) {
      return data;
    }
  },
  // callbacks
  beforeSubmit: function(form) {
    // ...
  },
  valid: function(form) {
    // ...
  },
  invalid: function(form, errors) {
    // ...
  },
  validation: function(form) {
    // ...
  },
  msgShow: function($msgbox, type) {
    // ...
  },
  msgHide: function($msgbox, type) {
    // ...
  },
);

7. API methods:

// clear messages
$('#form').validator("cleanUp");

// destroy the plugin
$('#form').validator("destroy");

// check if is valid
$('#field').isValid(function(v){
  if (v) {
   // do something
  }
});

// update options
$.validator.config({
  // options here
});

// set theme
$.validator.setTheme("myTheme", {
  // options here
});

// test validation rule
$('#form').test(elem, rule);

// set form field
$('#form').setField(key, field);
$('#form')..setField(obj);

// show/hide messages
$('#form').showMsg(elem, obj);
$('#form').hideMsg(elem);

// prevent duplicate submit
$('#form').holdSubmit(hold);

8. Events:

$('#form').on('validation', function(e, current){
  // do something...
});

$('#form').on('valid.form', function(e, form){
  // do something...
});

$('#form').on('invalid.form', function(e, form, errors){
  // do something...
});

$('#username').on('valid.field', function(e, result){
  // do something...
});

$('#username').on('invalid.field', function(e, result){
  // do something...
});

$('#username').on('valid.rule', function(e, ruleName){
  if (ruleName === 'remote') {
    // do something...
  }
});

$('#username').on('invalid.rule', function(e, ruleName){
  if (ruleName === 'remote') {
    // do something...
  }
});

This awesome jQuery plugin is developed by niceue. For more Advanced Usages, please check the demo page or visit the official website.