- Overview
- Documents
Verify.js is a powerful, customizable asynchronous form validation library.
Features
- Unobtrusive
- Easily extendable
- Configurable validators using per-element parameters
- Fully customisable asynchronous validation rules
- Grouped validation rules
Include
<!-- 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>
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>
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 |
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>
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>
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") andr.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>
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>
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 |
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
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:
- "Valid"
- "Skip" (Meaning the field was hidden or has no validators)
- 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 || ''); } });