Verify.js

A powerful, customizable, asynchronous form validation library – Custom and Asynchronous Rules, Errors Highlihting and Validation Tracking

A powerful, customizable asynchronous form validation library

Introduction

Features

  • Unobtrusive
  • Easily extendable
  • Configurable validations with parameters
  • Fully customisable asynchronous validations
  • Grouped validations

Include

Download

With Notify.js (http://notifyjs.com)

  • Production – verify.notify.min.js
  • Development – verify.notify.js

Without Notify.js

  • Production – verifyjs.min.js
  • Development – verify.js
Note Without Notify.js, you will need to implement a Prompt Handler in order to see validation results.

GitHub Hosted

<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

<!-- Verify.js (with Notify.js included) -->
<script src="//raw.github.com/jpillora/verifyjs/gh-pages/dist/verify.notify.min.js"></script>
Watch out ! This website is hosted on GitHub Pages and this link may be subject to bandwidth limits.

Basic

Usage

Add some validation rules

<form>
  <input value="42" data-validate="number">
  <input value="xx" data-validate="number">
  <input type="submit" class="submit">
</form>
Note Verify.js will auto-initialise all forms that contain an element with a data-validate attribute. Since we’re just using defaults settings, no extra code is required.

Included Rules

This is a list of all of the validation rules that come pre-packaged and will work out of the box.

Name Parameters Description
required None The value of the element cannot be blank
email None Ensures valid email format
url None Ensures valid URL format
number None Ensures only digits
numberSpace None Ensures only digits and spaces
alphaNumeric None Ensures only digits and letters
currency None Ensures a monetary value (E.g. $34.95)
decimal places (default: 2) Ensures a decimal value (E.g. 83.415). Will round to ‘places’ places.
regex or pattern regular expression,error message (default: “Invalid format”) Ensures the specified regular expression matches
phone None Ensures an Australian phone number
min min Ensures that at least ‘min’ number of characters exist
max max Ensures that at most ‘max’ number of characters exist
size length Ensures that exactly ‘length’ number of characters exist
size min,max Ensures that between ‘min’ and ‘max’ number of characters exist
minVal minVal Ensures that the value of the field is greater than or equal to ‘minVal’
maxVal maxVal Ensures that the value of the field is less than or equal to ‘maxVal’
rangeVal minVal,maxVal Ensures that the value of the field is between ‘minVal’ and ‘maxVal’
agreement None Ensures that the checkbox has been checked
minAge age Ensures that the date of birth equates to a minimum age of ‘age’
and many more yet to be documented…

Multiple Rules

You can also add multiple validation rules

<form>
  <input name="num" value="" data-validate="required,number">
  <input type="submit" class="submit">
</form>
Note You can use any combination of validation rules. Each field will execute it’s validation rules in sequence, even asynchronous rules ! See Execution Sequence for more information.

Configuring Rules

Some rules may also accept arguments

<form>
  <input name="a" value="abdef" data-validate="regex(abc,Must contain abc)">
  <input type="submit" class="submit">
</form>

Custom Validation

Custom Rules

If the validation rule you’re looking for isn’t in the list above, it’s easy to create your own custom rule.

For example, if for some strange reason, we wanted to check if a field is divible by 3, we can add a new ruledivisibleByThree.

$.verify.addRules({
  divisibleByThree: function(r) {
    var n = parseInt(r.val());
    if(n%3 !== 0)
      return "Not divisible by 3!"
    return true;
  }
});

Now, we can use it

<form>
  <input name="num" value="5" data-validate="divisibleByThree">
  <input type="submit" class="submit">
</form>
 Note See the Rule Object Spec for more information.

Asynchronous Rules

They key to asynchronous rules is just to use the Rule Object‘s callback method. So instead of return "Failed" and return true , we’ll now use r.callback("Failed") and r.callback(true). By not returning (which will actually returns undefined), you’re telling the library to wait for a callback.
If no callback is fired, a timeout warning will be displayed in the console.

The above is exemplied here:

$.verify.addRules({
  myAjax: function(r) {
    //Give the user some feedback (uses the Prompt Handler)
    r.prompt(r.field, "Loading...", "black");
    //Simulate delay
    setTimeout(function() {
      var result;
      if(Math.random() > 0.5)
        result = true;
      else
        result = "My Ajax Failed";
      r.callback(result);
    }, 2000);
  }
});

Now, we can use it

<form>
  <input name="num" value="42" data-validate="myAjax">
  <input type="submit" class="submit">
</form>
Note Asynchronous rules execute in the same sequence as synchronous rules. SeeExecution Sequencefor more information.

Advanced Validation
Groups

Group validations are required when validation depends on two or more fields. Useful for checking the combined result of a set of fields, such as a date range.

Group validations are defined in the same way as field (or single) validations, except you can provide two extra peices of optionally information:

Group ID is generally required in most cases.
It will provide an easy way to tag given elements in the context of validation. For example, the date range rule requires a start and an end date in order to begin validation.
Read about the Require IDs Option.

Group Scope is for reasonably rare cases when you are using the same group validation rule more than once in a single form. For example, if you were to have two date validators on one form, you would use group scope to allow the library differentiate between the two.

Group validations are in the following format: name[.scope][#id][(args …)]

Dange range could be used like so:

<form>
  <input value="3/1/2x13" data-validate="date,dateRange#start">
  <input value="2/1/2013" data-validate="date,dateRange#end">
  <input type="submit" class="submit">
</form>

Group Errors

By default the error prompt will NOT be displayed on each member of the group, instead, only the field that triggered validation will display the message.

This can be overriden by instead returning a map of ids to strings, as shown here:

$.verify.addGroupRules({
  myGroup: function(r) {
    return { a: "An error for 'a'", c: "An error for 'c'"};
  }
});
<form>
  <input data-validate="myGroup#a">
  <input data-validate="myGroup#b">
  <input data-validate="myGroup#c">
  <input type="submit" class="submit">
</form>
Note If the group validation is asynchronous, user.callback({ ... }).

Execution Sequence

In order to better understand what’s actually happening when you submit the form, I’ve included this nice diagram:

Diagram in progress !

API

Configure

Method Description Parameters
$.verify({…}) Override the global options object An Options Object
$("form").verify({…}) Enable and/or override the options of a selected form An Options Object
Note $("form").verify() gets automatically called on DOM ready (using default options). Though the above method will be required when dynamically adding new forms to the page.

Adding Rules

Method Description Parameters
$.verify.addRules({…}) Add new field rules A map (Object) of rule names to Definition Objects.
$.verify.addGroupRules({…}) Add new group rules A map (Object) of rule names to Definition Objects.
$.verify.updateRules({…}) Update existing rules A map (Object) of rule names to Definition Objects. Only existing rules will be updated.

The difference between field and group rules is largely outlined in the Groups section above. There are also differences in the Rule Object of each.

Definition Object

Property Type Description
fn Function The rule entry point (required)
extend String The name of the parent rule to extend
regex RegExp A regular expression used to construct a fn property
anything Any A variable that will be passed to the Rule Object

If your rule only has the one ‘fn’ property:

$.verify.addRules({
  myRule: {
    fn: function(r) {
      return r.val() === "42" ? true : "Wasn't 42";
    }
  }
});

Then it can be shortened to:

$.verify.addRules({
  myRule: function(r) {
    return r.val() === "42" ? true : "Wasn't 42";
  }
});

Regular expression shortcut:

$.verify.addRules({
  myRule: {
    regex: /^[ab]+$/i
    message: "It contained something other than 'a's and 'b's"
  }
});

So if the rule has a regex and an optional message property, its fn property will automatically built.

Use of variables:

$.verify.addRules({
  myRule: {
    expected: "42",
    message: "Wasn't 42",
    fn: function(r) {
      return r.val() === r.expected ? true : r.message;
    }
  }
});

The above example isn’t very exciting, though when it comes time to use multiple languages, you can just update the message:

$.verify.updateRules({
  myRule: {
    message: "no tuvo éxito"
  }
});

Now, getting abit fancier, we can extend existing rules with the extend property

$.verify.addRules({
  myRule: {
    message: "An error",
    
    common: function(n) {
      //a useful task...
    },
    
    fn: function(r) {
      r.common(21);
      return r.message;
    }
  },
  
  //Alternative uses of 'common'
  myOtherRule: {
    extend: "myRule",
    
    fn: function(r) {
      r.common(42);
      return r.message; //"An Error"
    }
  },
  
  //Only modify the 'message'
  myThirdRule: {
    extend: "myRule",
    message: "A super bad error"
  }
});

Rule Object

The Rule Object is the single parameter in all validation rules. It is known as r in the examples.

Type Property Type Description Parameters
Field Only field JQuery Object A reference to element being validated None
val() Function An alias tor.field.val() None (Getter) / Value (Setter)
Group Only field(id) Function Gets a field by group ID id
val(id) Function An alias tor.field(id).val() id (Getter) / id,Value (Setter)
Documentation in progress…

Selector API

Method Description Parameters
$(“#my-form”).validate(…) Programmatically trigger validation on every element in the form. callback(success)
$(“#my-text-input”).validate(…) Programmatically trigger validation on a single element. callback(success)

Options

How To Option

There are two levels of options:

  • Global Options
  • Form Specific Options

The form specific options prototypically inherit from the global options. Since they aren’t copied, any changes to the globals will propogate through to each validation form on the page.

These options can be changed using the Configure API above.

 

Name Description Default
debug Display log messages flag false
validateAttribute Attribute to use for listing validation rules “data-validate”
validationEventTrigger Event which will trigger validation “blur”
scroll Automatically scroll viewport to the first error true
focusFirstField Automatically focus into to the first field with an error true
hideErrorOnChange Hide error while the user is editing the field false
skipHiddenFields Whether to skip the hidden fields with validators true
errorContainer A function which returns the element in which to add or remove the “errorClass” function(input) { return input; }
errorClass The class name to be toggled on the “errorContainer” “error”
beforeSubmit Pre-form-submit hook. If you return true, form will submit. function(form, result) { return result; }
track Method used for tracking user validation interactions. Read more here Validation Tracking $.noop
prompt Method used to display validation errors. Read more here Prompt Handler function(element, text, opts) { $.notify(element, text, opts); }

Validation Tracking

The Validation Tracking Handler is a function which looks like function(type, fieldId, result)

  • type – Currently, there is only one type: "Validate"
  • fieldId – Field Identifier is made up of the form name followed by the field name. Name is id attribute, otherwise falls back to the name attribute, otherwise falls back to a randomly generated ID.
  • result – The validation result will be one of:
    1. "Valid"
    2. "Skip" (Meaning the field was hidden or has no validators)
    3. The error message that was displayed on the field

This was intended for use with Google Analytics Event Tracking.
Following it’s 3 column implementation: Category, Action and Label.

An example function to track validations using Google Analytics might be something like:

$.verify({
  track: function(type, fieldId, result) {
    if(_gaq) _gaq.push(['_trackEvent', type, fieldId, result]);
  }
});

Also note, only validations triggered from the validationEventTrigger (“blur” by default) will be tracked. This prevents false positives from early form validations.

Prompt Handler

The Prompt Handler is a function which looks like function(element, text[, opts]). So a really simple function might be:

$.verify({
  prompt: function(element, text) {
    alert(text);
  }
});

Or you might want to get abit more fancy with some assistance of HTML:

<input type='text' data-validate='required'/>
<span class='tip'></span>
$.verify({
  prompt: function(element, text) {
    element.siblings(".tip").html(text || '');
  }
});
Pro Tip The text parameter will be null when there is no error, thereby clearing the error.

Or you could get even fancier and include Notify.js by downloading the packaged version and then you don’t have to worry about making your own Prompt Handler.

$.verify({
  // no options required !
});

Also note,
Notify.js allows you make custom prompt styles and themes as opposed to the standard bootstrap alert style.

The Githubs

Contributing

Contributing is easy as

  1. Fork
  2. npm install
  3. grunt

Node and Grunt 4.x required.

You can also bug reports on GitHub Issues and I should get on it reasonable quickly.

Credits

Thanks to @posabsolute as this plugin was originally a fork of jQuery Validation Engine though it has now been completely rewritten. Many good ideas we’re reimplemented like the list of validators inside an attribute. New goals are to be fully asynchronous, easily extendable and to have a cleaner code base.