http://rickharrison.github.io/validate.js/
https://gist.github.com/musicm122/9635212
http://www.benjaminkeen.com/open-source-projects/smaller-projects/really-simple-validation-js/
http://jqueryvalidation.org/
http://1000hz.github.io/bootstrap-validator/
http://formvalidation.io/
http://stackoverflow.com/questions/18296267/form-validation-with-bootstrap-jquery
http://twitterbootstrap.org/bootstrap-form-validation/
https://github.com/wpic/bootstrap.validator.js
Why should we use the jQuery Validation plugin?
The jQuery Validation plugin makes clientside validation trivial, while offering lots of option for customization. The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods.
All bundled methods come with default error messages in english and translations into 32 languages.
What is the purpose of the showErrors option?
A custom message display handler. Gets the map of errors as the first argument and and array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().
// Update the number of invalid elements each time an error is displayed.
// Delegates to the default implementation for the actual error display.
$(".selector").validate({
showErrors: function(errorMap, errorList) {
$("#summary").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
})
What is the purpose of the errorPlacement option?
Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.
// Use a table layout for the form, placing error messags in the next cell after the input.
$("#myform").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
debug:true
})
What are the recommendations on form fields?
Each input has a label associated with it: The for-attribute of the label refers to the id-attribute of the input.
<label for="firstname">Firstname</label><input id="firstname" name="fname" />
The name attribute is required for input elements, the validation plugin doesn't work without it. Usually name and id attributes should have the same value.
Does jQuery Validation support depend-rules?
Yes.
// Specifies a contact element as required and as email address, the latter depending on
// a checkbox being checked for contacting via email.
$(".selector").validate({
rules: {
contact: {
required: true,
email: {
depends: function(element) {
return $("#contactform_email:checked")
}
}
}
}
})
How can we write custom validation method?
This plugin provides a lot of validation method. However, you can also write your own custom validation method. Except for "required" and "equalTo", all validation methods declare an element valid when it has no value at all. That way an email field is optional, unless "required" is specified. you can specify an element input to contain a valid email address, or nothing at all. Use $.validator.addMethod to implement custom methods.
How can we validate multiple fields with one method?
Using a combination of custom methods, the groups-option and, when necessary, custom error placement, you can validate multiple fields with one method and display a single message for them.
How many ways can we specify rules?
A validation rule applies one or more validation methods to an input element. You can specify validation rules via metadata or via plugin settings (option rules). The decision is often influenced by serverside infrastructure. If a web framework is used, its often easier to use metadata, which is also good for fast prototyping. Plugin settings produce cleaner markup, though valid markup results from both.
How can we deal with fields that have complex names (brackets and dots)?
If your form consists of fields using names that aren't legal JavaScript identifiers, you have to quote those names when using the rules option:
$("#myform").validate({
rules: {
// no quoting necessary
name: "required",
// quoting necessary!
"user[email]": "email",
// dots need quoting, too!
"user.address.street": "required"
}
});
Can this plugin handle multiple forms?
Yes and no. This plugin can handle only one form per call. In case you have multiple forms on a single page which you want to validate, you would have to invoke validate() on each form:
$('#form1').validate({...});
$('#form2').validate({...});
You can avoid having to duplicate the plugin settings by modifying the defaults. Use $.validator.setDefaults({…}) to override multiple settings at once.
How can we refactor rules?
Whenever you have multiple fields with the same rules and messages, refactoring those can reduce a lot of duplication. Using addMethod and addClassRules are most effective for that.
Lets consider an example where you have ten customer fields, each is required and has a minlength of 2. You need custom messages for both rules. To avoid having to specify those rules and messages again and again, we can alias existing methods with different messages and group them into a single class:
// alias required to cRequired with new message
$.validator.addMethod("cRequired", $.validator.methods.required,
"Customer name required");
// alias minlength, too
$.validator.addMethod("cMinlength", $.validator.methods.minlength,
// leverage parameter replacement for minlength, {0} gets replaced with 2
$.format("Customer name must have at least {0} characters"));
// combine them both, including the parameter for minlength
$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });
With that in place, we can add a class customer to all customer fields and be done with it:
<input name="customer1" class="customer" />
<input name="customer2" class="customer" />
<input name="customer3" class="customer" />
What are the three ways to specify error messages?
An error message displays a hint for the user about invalid elements, and what is wrong. There are three ways to provide error messages:
- via the title attribute of the input element
- via error labels
- via plugin settings (option messages).
All included validation rules provide a default error message which you can use for prototyping, because it is used when no specific message is provided.
The priorities are as follows: A custom message (passed by plugin options), the element's title, the default message.
Google Toolbar's AutoFill feature sometimes conflicts with the validation plugin's message display. Google Toolbar replaces the title attribute of an element with some hint at it's AutoFill. The validation plugin then uses that title attribute to display it as an error message - not the intended behaviour. One workaround to avoid that is to clear affected elements on DOM load:
$("input.remove_title").attr("title", "");
Or specify the error message via plugin settings (option messages).
See this article.
How is the error message displayed?
Error messages are handled via label elements with an additional class (option errorClass). The link between the message and the invalid element is provided via the label's for attribute. When provided in the markup, they are shown and hidden accordingly, otherwise created on demand. By default, labels are created after the invalid element, this is also customizable (option errorPlacement). It is also possible to put them into an error container (option errorLabelContainer). To use a different element then a label, specify the errorElement option.
How can we display a general message?
In addition to field-specific messages you can display a general "your form is invalid, please fix the highlighted fields!" message in a container anywhere on your page, eg. above the form (option errorContainer). The container is shown and hidden when errors occur and are fixed accordingly. The container for error labels (option errorLabelContainer) can also be nested inside the error container.
How does this plugin handle focusing on invalid element?
By default, the first invalid element in a form is focused after submitting a form with invalid elements. To prevent confusion on the behalf of the user, the plugin remembers the element that had focus when the form was submitted, and refocuses that element. That way the user can try to fill out elements of the form at the end, without being forced to focus them again and again. This can be disabled (option focusInvalid).
How does this plugin behave?
By default, forms are validated on submit, triggered by the user clicking the submit button or pressing enter when a form input is focused (option onsubmit). In addition, once a field was highlighted as being invalid, it is validated whenever the user types something in the field (option onkeyup). When the user enters something invalid into a valid field, it is also validated when the field loses focus (option onblur).
The goal of these interactions is to provide feedback as early as possible, while avoid to annoy users. Displaying error messages before the user had the chance to even type something is not helpful.
What are the general behaviors:
After trying to submit an invalid form, the first invalid element is focused, allowing the user to correct the field. If another invalid field, that wasn't the first one, was focused before submit, that field is focused instead, allowing the user start at the bottom, if he prefers that.
Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages - he won't get bugged before he had the chance to actually enter a correct value
Once a field was marked invalid, it is eagerly validated: As soon as the user entered the necessary value, the error message is removed.
If the user enters something in a non-marked field, and tabs/clicks away from it (blur the field), it is validated - obviously the user had the intention to enter something, but failed to enter the correct value.
What is the purpose of the $('selector').validate() method?
It associate this plugin with a form or a particular element. It does not do the actual validation.
What is the purpose of the $('selector').valid() method?
Checks whether the selected form is valid. The validate() method needs to be called on the form before this method is used.
What is the purpose of jQuery.validator.format( template, …) utility function?
The jQuery.validator.format( template, …) utility function takes multiple arguments. The first argument is a string which is used as a template. This template contains token of form {n} where n is a number. Example:
$("button").click(function () {
var str = "Hello {0}, this is {1}";
str = jQuery.validator.format(str, "World", "Bob");
alert(str);
}
What is the purpose of the form() method?
Validates the form, returns true if it is valid, false otherwise. This behaves as a normal submit event, but returns the result.
What is the purpose of the element(element) method?
Validates a single element, returns true if it is valid, false otherwise. This behaves as validation on blur or keyup, but returns the result. This method take one argument which is a selector for the element you want to validate. This element must be inside the validated form.
What is the purpose of showErrors(errors) method?
Show the specified messages. Keys have to refer to the names of elements, values are displayed for those elements, using the configured error placement. This method takes one argument which is a mapping of one or more key/value pairs of input names and messages.
What is the purpose of numberOfInvalids( ) method?
Returns the number of invalid fields. This depends on the internal validator state. It covers all fields only after validating the complete form (on submit or via $("form").valid()). After validating a single element, only that element is counted. Most useful in combination with the invalidHandler-option.
What is the purpose of setDefaults(defaults) static method?
Modify default settings for validation. Accepts everything that Plugins/Validation/validate accepts.
What is the purpose of addMethod( name, method, message ) static method?
Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.
Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: http://regexlib.com/DisplayPatterns.aspx
name: The name of the method, used to identify and referencing it, must be a valid javascript identifier.
method: The actual method implementation, returning true if an element is valid.
message: The default message to display for this method. Can be a function created by jQuery.validator.format(value). When undefined, an already existing message is used (handy for localization), otherwise the field-specific messages have to be defined.
// Add a validation method that checks if a value starts with a certain domain.
jQuery.validator.addMethod("domain", function(value, element) {
return this.optional(element) || /^http:\/\/mycorporatedomain.com/.test(value);
}, "Please specify the correct domain for your documents");
// Adds a validation method that checks if a given value equals the addition of the two parameters.
jQuery.validator.addMethod("math", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.format("Please enter the correct value for {0} + {1}"));
What is the purpose of the addClassRules( name, rules ) static method?
Add a compound class method - useful to refactor common combinations of rules into a single class.
name: (String) The name of the class rule to add.
rules: (Options) The compound rules (see example).
// Add a new compound rule called "name", replacing class="required" minlength="2" with class="name".
jQuery.validator.addClassRules("name", {
required: true,
minlength: 2
});
What is the purpose of the addClassRules( rules ) static method?
Add compound class methods - useful to refactor common combinations of rules.
rules: (Options) A map of className-rules pairs (see example).
// Add two compound class rules for name and zip.
jQuery.validator.addClassRules({
name: {
required: true,
minlength: 2
},
zip: {
required: true,
digits: true,
minlength: 5,
maxlength: 5
}
});
What is the purpose of submitHandler option?
Specifies a callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.
// Submits the form via Ajax when valid.
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
})
// Use submitHandler to process something and then using the default submit. Note that "form" refers to a DOM element, this way the validation isn't triggered again.
$(".selector").validate({
submitHandler: function(form) {
// do other stuff for a valid form
form.submit();
}
})
What is the purpose of the invalidHandler option?
Specifies a callback function for when an invalid form is submitted. Called with a event object as the first argument, and the validator as the second.
// Displays a message above the form, indicating how many fields are invalid when the user tries to submit an invalid form.
$(".selector").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
})
What is the purpose of the messages option?
Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope of the validator and with the rule's parameters as the first and the element as the second arugment, it must return a String to display as the message.
// Specifies a name element as required and an email element as required and a valid email address.
// A single message is specified for the name element, and two messages for email.
$(".selector").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please specify your name",
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name@domain.com"
}
}
})
// Validates the name-field as required and having at least two characters.
// Provides a callback message using jQuery.format to avoid having to specify the parameter in two places.
$(".selector").validate({
rules: {
name: {
required: true,
minlength: 2
}
},
messages: {
name: {
required: "We need your email address to contact you",
minlength: jQuery.format("At least {0} characters required!")
}
}
})
What is the purpose of "groups" option?
Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use errorPlacement to control where the group message is placed.
// Use a table layout for the form, placing error messags in the next cell after the input.
$("#myform").validate({
groups: {
username: "fname lname"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "fname"
|| element.attr("name") == "lname" )
error.insertAfter("#lastname");
else
error.insertAfter(element);
},
debug:true
})
How can we use the onsubmit, onfocusout, onkeyup, onclick options?
These options are boolean which control whether validation should be invoked when the corresponding event happens.
What is the purpose of the errorClass option?
Use this class to create error labels, to look for existing error labels and to add it to invalid elements.
// Sets the error class to "invalid".
$(".selector").validate({
errorClass: "invalid"
})
What is the purpose of the validClass option?
This class is added to an element after it was validated and considered valid.
// Sets the valid class to "success".
$(".selector").validate({
validClass: "success"
})
What is the meaning of the errorElement option?
Use this element type to create error messages and to look for existing error messages. The default, "label", has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, no matter the element type).
// Sets the error element to "em".
$(".selector").validate({
errorElement: "em"
})
What is the purpose of the wrapper option?
Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages.
// Wrap each error element with a list item, useful when using an ordered or unordered list as the error container.
$(".selector").validate({
wrapper: "li"
})
What is the purpose of errorLabelContainer option?
It is a selector. Hide and show this container when validating.
// All error labels are displayed inside an unordered list with the ID "messageBox", as specified by
// the selector passed as errorContainer option. All error elements are wrapped inside an li element, to create a list of messages.
$("#myform").validate({
errorLabelContainer: "#messageBox",
wrapper: "li",
submitHandler: function() { alert("Submitted!") }
})
What is the purpose of the errorContainer option?
Hide and show this container when validating.
// Uses an additonal container for error messages. The elements given as the errorContainer are all shown
// and hidden when errors occur. But the error labels themselve are added to the element(s) given as
// errorLabelContainer, here an unordered list. Therefore the error labels are also wrapped into li elements (wrapper option).
$("#myform").validate({
errorContainer: "#messageBox1, #messageBox2",
errorLabelContainer: "#messageBox1 ul",
wrapper: "li", debug:true,
submitHandler: function() { alert("Submitted!") }
})
What is the purpose of "success" option?
If specified, the error label is displayed to show a valid element. If a String is given, its added as a class to the label. If a Function is given, its called with the label (as a jQuery object) as its only argument.
// Add a class "valid" to valid elements, styled via CSS.
$("#myform").validate({
success: "valid",
submitHandler: function() { alert("Submitted!") }
})
What is the purpose of highlight option?
How can we highlight invalid fields. Override to decide which fields and how to highlight.
Default: Adds errorClass (see the option) to the element.
// Highlights an invalid element by fading it out and in again.
$(".selector").validate({
highlight: function(element, errorClass) {
$(element).fadeOut(function() {
$(element).fadeIn();
});
}
})
What is the purpose of unhighlight option?
Called to revert changes made by option highlight, same arguments as highlight.
What is the purpose of the ignoreTitle option?
Set to skip reading messages from the title attribute, helps to avoid issues with Google Toolbar; default is false for compability, the message-from-title is likely to be completely removed in a future release.
What is the purpose of the validate() method?
The validate() method set up event handlers for submit, focus, keyup, blur, and trigger validation of the entire form or individual elements. Each one can be disabled, see the onxxx (onsubmit, onfocusout, onkeyup, onclick) options.
What is the purpose of invalidHandler?
Use invalidHandler to react when an invalid form is submitted. The invalidHandler option specifies a callback function for when an invalid form is submitted. Called with a event object as the first argument, and the validator as the second.
// Displays a message above the form, indicating how many fields are invalid when the user tries to submit an invalid form.
$(".selector").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
})
What is the purpose of focusInvalid option?
focusInvalid focus elements when submitting an invalid form.
What is the purpose of the debug option?
The debug option always prevents the default submit, even when script error occur.
What is the purpose of the submitHandler option?
Use the submitHandler to implement your own form submit (eg. via Ajax). The submitHandler option specifies a callback function for handling the actual submit when the form is valid. This function get the form as the only argument.
// Submit the form via Ajax when valid
$('.selector').validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
// Use submitHandler to process something and then using the default submit.
// Note that "form" is a DOM element. This way, the validation isn't triggered again.
$('.selector').validate({
submitHandler: function(form) {
// do something
form.submit();
}
});