jQuery Validate
The jQuery Validate plugin provides powerful form validation features, making client-side form validation simpler, while offering a wide range of customization options to meet various application needs. The plugin comes bundled with a set of useful validation methods, including URL and email validation, and provides an API for writing custom methods. All bundled methods default to using English for error messages and are translated into 37 other languages.
This plugin was written and is maintained by Jörn Zaefferer, a member of the jQuery team, a lead developer on the jQuery UI team, and the maintainer of QUnit. The plugin began in the early days of jQuery in 2006 and has been updated ever since. The current version is 1.14.0.
Visit the jQuery Validate official website to download the latest version of the jQuery Validate plugin.
Download link for version 1.14.0 provided by tutorialpro.org: http://static.tutorialpro.org/download/jquery-validation-1.14.0.zip
Importing the JS Library (using tutorialpro.org's CDN)
<script src="http://static.tutorialpro.org/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.tutorialpro.org/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
Default Validation Rules
No. | Rule | Description |
---|---|---|
1 | required:true | Field must be filled out. |
2 | remote:"check.php" | Use ajax to call check.php to validate the input. |
3 | email:true | Must be a valid email address. |
4 | url:true | Must be a valid URL. |
5 | date:true | Must be a valid date. Date validation fails in IE6, use with caution. |
6 | dateISO:true | Must be a valid date (ISO), e.g., 2009-06-23, 1998/01/22. Only validates format, not validity. |
7 | number:true | Must be a valid number (negative and decimal). |
8 | digits:true | Must be an integer. |
9 | creditcard: | Must be a valid credit card number. |
10 | equalTo:"#field" | Input must be the same as #field. |
11 | accept: | Input must be a string with a valid suffix (for file uploads). |
12 | maxlength:5 | Input length cannot exceed 5 characters (Chinese characters count as one). |
13 | minlength:10 | Input length must be at least 10 characters (Chinese characters count as one). |
14 | rangelength:[5,10] | Input length must be between 5 and 10 characters (Chinese characters count as one). |
15 | range:[5,10] | Input value must be between 5 and 10. |
16 | max:5 | Input value cannot be greater than 5. |
17 | min:10 | Input value cannot be less than 10. |
Default Messages
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
maxlength: $.validator.format("Please enter no more than {0} characters."),
minlength: $.validator.format("Please enter at least {0} characters."),
rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
range: $.validator.format("Please enter a value between {0} and {1}."),
max: $.validator.format("Please enter a value less than or equal to {0}."),
min: $.validator.format("Please enter a value greater than or equal to {0}.")
}
jQuery Validate provides a Chinese language message pack, located in the download package at dist/localization/messages_zh.js, with the following content:
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery", "../jquery.validate"], factory );
} else {
factory( jQuery );
}
}(function( $ ) {
/*
* Translated default messages for the jQuery validation plugin.
* Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語)
*/
$.extend($.validator.messages, {
required: "这是必填字段",
remote: "请修正此字段",
email: "请输入有效的电子邮件地址",
url: "请输入有效的网址",
date: "请输入有效的日期",
dateISO: "请输入有效的日期 (YYYY-MM-DD)",
number: "请输入有效的数字",
digits: "只能输入数字",
creditcard: "请输入有效的信用卡号码",
equalTo: "你的输入不相同",
extension: "请输入有效的后缀",
maxlength: $.validator.format("最多可以输入 {0} 个字符"),
minlength: $.validator.format("最少要输入 {0} 个字符"),
rangelength: $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"),
range: $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"),
max: $.validator.format("请输入不大于 {0} 的数值"),
min: $.validator.format("请输入不小于 {0} 的数值")
});
}));
You can include this localization message file, dist/localization/messages_zh.js, in your page:
<script src="http://static.tutorialpro.org/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
Usage
1. Write Validation Rules into Controls
<script src="http://static.tutorialpro.org/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.tutorialpro.org/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.tutorialpro.org/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script>
$.validator.setDefaults({
submitHandler: function() {
alert("Submitted!");
}
});
$().ready(function() {
$("#commentForm").validate();
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Enter your name, email, URL, and comment.</legend>
<p>
<label for="cname">Name (required, at least two characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
2. Write validation rules in JavaScript code
$().ready(function() {
// Validate the form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
username: {
required: "Please enter a username",
minlength: "Username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy",
topic: "Please select at least two topics"
}
});
});
If a control does not have a message, the default message will be called.
<form class="cmxform" id="signupForm" method="get" action="">
<fieldset>
<legend>Validate Full Form</legend>
<p>
<label for="firstname">First Name</label>
<input id="firstname" name="firstname" type="text">
</p>
<p>
<label for="lastname">Last Name</label>
<input id="lastname" name="lastname" type="text">
</p>
<p>
<label for="username">Username</label>
<input id="username" name="username" type="text">
</p>
<p>
<label for="password">Password</label>
<input id="password" name="password" type="password">
</p>
<p>
<label for="confirm_password">Confirm Password</label>
<input id="confirm_password" name="confirm_password" type="password">
</p>
<p>
<label for="email">Email</label>
<input id="email" name="email" type="email">
</p>
<p>
<label for="agree">Please accept our policy</label>
<input type="checkbox" class="checkbox" id="agree" name="agree">
</p>
<p>
<label for="newsletter">I would like to receive new information</label>
<input type="checkbox" class="checkbox" id="newsletter" name="newsletter">
</p>
<fieldset id="newsletter_topics">
<legend>Topics (at least select two) - Note: If "I would like to receive new information" is not checked, the following options will be hidden, but we make it visible here for demonstration purposes</legend>
<label for="topic_marketflash">
<input type="checkbox" id="topic_marketflash" value="marketflash" name="topic">Marketflash
</label>
<label for="topic_fuzz">
<input type="checkbox" id="topic_fuzz" value="fuzz" name="topic">Latest fuzz
</label>
<label for="topic_digester">
<input type="checkbox" id="topic_digester" value="digester" name="topic">Mailing list digester
</label>
<label for="topic" class="error">Please select at least two topics you'd like to receive.</label>
</fieldset>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
required: true means the value is mandatory. required: "#aa:checked" means validation is required if the expression is true. required: function(){} means validation is required if the function returns true.
The latter two are often used for elements that need to be filled or left empty together in a form.
Common Methods and Issues to Watch For
1. Use alternative methods instead of the default SUBMIT
$().ready(function() {
$("#signupForm").validate({
submitHandler: function(form) {
alert("Submit event!");
form.submit();
}
});
});
Using AJAX method:
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
You can set default values for validate as follows:
$.validator.setDefaults({
submitHandler: function(form) { alert("Submit event!"); form.submit(); }
});
To submit the form, use form.submit()
instead of $(form).submit()
.
2. Debug, validate without submitting the form
If this parameter is true, the form will not be submitted, only validated, which is very convenient for debugging.
$().ready(function() {
$("#signupForm").validate({
debug: true
});
});
If you want multiple forms on a page to be in debug mode, use:
$.validator.setDefaults({
debug: true
});
3. Ignore: Ignore certain elements from validation
ignore: ".ignore"
4. Change the position where error messages are displayed
errorPlacement: Callback
Specifies the position where errors should be placed. By default, errors are appended to the parent of the element being validated: error.appendTo(element.parent());
.
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
Example
<p>Place error messages after the label element and wrap them in a span element</p>
<form method="get" class="cmxform" id="form1" action="">
<fieldset>
<legend>Login Form</legend>
<p>
<label for="user">Username</label>
<input id="user" name="user" required minlength="3">
</p>
<p>
<label for="password">Password</label>
<input id="password" type="password" maxlength="12" name="password" required minlength="5">
</p>
<p>
<input class="submit" type="submit" value="Login">
</p>
</fieldset>
</form>
The code's function is to display error messages in <td class="status"></td>
normally, but for radio buttons, display them in <td></td>
, and for checkboxes, display them after the content.
Parameter | Type | Description | Default Value |
---|---|---|---|
errorClass | String | Specifies the CSS class name for error messages, allowing customization of error message styles. | "error" |
errorElement | String | Specifies what tag to use to mark errors, default is label, can be changed to em. | "label" |
errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"
5. Change Error Message Display Style
Set the style for error messages, which can include icon display. A validation.css has already been established in this system specifically for maintaining the style of validation files.
input.error { border: 1px solid red; }
label.error {
background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;
padding-left: 16px;
padding-bottom: 2px;
font-weight: bold;
color: #EA5200;
}
label.checked {
background:url("./demo/images/checked.gif") no-repeat 0px 0px;
}
6. Function to Execute on Field Validation Success
success: String, Callback
Action to take when the element being validated passes validation. If followed by a string, it will be treated as a CSS class; it can also be followed by a function.
success: function(label) {
// set as text for IE
label.html(" ").addClass("checked");
//label.addClass("valid").text("Ok!")
}
Add "valid" to the validated element, with styles defined in CSS <style>label.valid {}</style>.
success: "valid"
7. Modify Validation Trigger Methods
Although the following are boolean types, it is recommended not to add them unless changing to false.
Trigger Method | Type | Description | Default Value |
---|---|---|---|
onsubmit | Boolean | Validate on submission. Set to false to use other methods for validation. | true |
onfocusout | Boolean | Validate when losing focus (excluding checkboxes/radio buttons). | true |
onkeyup | Boolean | Validate on keyup. | true |
onclick | Boolean | Validate on clicking checkboxes and radio buttons. | true |
focusInvalid | Boolean | After form submission, focus on the first invalid form or the invalid form that had focus before submission. | true |
focusCleanup | Boolean | If true, remove error messages when an invalid element gains focus. Avoid using with focusInvalid. | false |
// Reset form
$().ready(function() {
var validator = $("#signupForm").validate({
submitHandler:function(form){
alert("submitted");
form.submit();
}
});
$("#reset").click(function() {
validator.resetForm();
});
});
8. Asynchronous Validation
remote: URL
Validate using AJAX. By default, it submits the current value being validated to the remote address. If other values need to be submitted, use the data option.
remote: "check-email.php"
remote: {
url: "check-email.php", // Backend handler
type: "post", // Data sending method
dataType: "json", // Data format received
data: { // Data to be sent
username: function() {
return $("#username").val();
}
}
}
The remote address can only output "true" or "false"; no other output is allowed.
9. Add Custom Validation
addMethod: name, method, message
Custom validation method
// Chinese characters are two bytes
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
var length = value.length;
for(var i = 0; i < value.length; i++){
if(value.charCodeAt(i) > 127){
length++;
}
}
return this.optional(element) || ( length >= param[0] && length <= param[1] );
}, $.validator.format("Please ensure the input value is between {0}-{1} bytes (one Chinese character counts as 2 bytes)"));
// Postal code validation
jQuery.validator.addMethod("isZipCode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "Please correctly fill in your postal code");
Note: Add in the additional-methods.js file or in the jquery.validate.js file. It is recommended to write in the additional-methods.js file.
Note: Add in the messages_cn.js file: isZipCode: "Can only include Chinese characters, English letters, numbers, and underscores". Ensure to reference the additional-methods.js file before calling.
10. Validation for Radio, Checkbox, and Select
Radio required means one must be selected.
<input type="radio" id="gender_male" value="m" name="gender" required />
<input type="radio" id="gender_female" value="f" name="gender"/>
Checkbox required means it must be checked.
<input type="checkbox" class="checkbox" id="agree" name="agree" required />
Checkbox minlength means the minimum number to be checked, maxlength means the maximum number to be checked, rangelength:[2,3] means the checked number range.
<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required minlength="2" />
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />
Select required means the selected value cannot be empty.
<select id="jungle" name="jungle" title="Please select something!" required>
<option value=""></option>
<option value="1">Buga</option>
<option value="2">Baga</option>
<option value="3">Oi</option>
</select>
Select minlength means the minimum number to be selected (for multi-select), maxlength means the maximum number to be selected, rangelength:[2,3] means the selected number range.
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
<option value="b">Banana</option>
<option value="a">Apple</option>
<option value="p">Peach</option>
<option value="t">Turtle</option>
</select>
jQuery.validate Chinese API
Name | Return Type | Description |
---|---|---|
validate(options) | Validator | Validate the selected FORM. |
valid() | Boolean | Check if validation passes. |
rules() | Options | Return the validation rules for the element. |
rules("add", rules) | Options | Add validation rules. |
rules("remove", rules) | Options | Remove validation rules. |
removeAttrs(attributes) | Options | Remove special attributes and return them. |
Custom Selectors | ||
:blank | Validator | Filter for elements with no value. |
:filled | Array <Element> | Filter for elements with a value. |
:unchecked | Array <Element> | Filter for elements not selected. |
Utility Tools | ||
jQuery.format(template, argument, argumentN...) | String | Replace {n} in the template with parameters. |
Validator
The validate method returns a Validator object. The Validator object has many methods that can trigger the validation process or change the form's content. Below are some of the commonly used methods.
| Name | Return Type | Description |
Form Validation Methods
Method | Return Type | Description |
---|---|---|
form() | Boolean | Validates the form and returns success or failure. |
element(element) | Boolean | Validates a single element and returns success or failure. |
resetForm() | undefined | Resets the form to its pre-validation state. |
showErrors(errors) | undefined | Displays specific error messages. |
Validator Functions | ||
setDefaults(defaults) | undefined | Changes the default settings. |
addMethod(name, method, message) | undefined | Adds a new validation method. Must include a unique name, a JavaScript method, and a default message. |
addClassRules(name, rules) | undefined | Adds combined validation types, useful when multiple validation methods are used within a class. |
addClassRules(rules) | undefined | Adds combined validation types, useful when multiple validation methods are used within a class. This adds multiple validation methods at once. |
Built-in Validation Methods
Name | Return Type | Description |
---|---|---|
required() | Boolean | Validates that the element is required. |
required(dependency-expression) | Boolean | Validates that the element is required based on the result of the expression. |
required(dependency-callback) | Boolean | Validates that the element is required based on the result of the callback function. |
remote(url) | Boolean | Requests remote validation. The URL is typically a remote method call. |
minlength(length) | Boolean | Sets the minimum length. |
maxlength(length) | Boolean | Sets the maximum length. |
rangelength(range) | Boolean | Sets a length range [min, max]. |
min(value) | Boolean | Sets the minimum value. |
max(value) | Boolean | Sets the maximum value. |
email() | Boolean | Validates email format. |
range(range) | Boolean | Sets the value range. |
url() | Boolean | Validates URL format. |
date() | Boolean | Validates date format (similar to 30/30/2008, does not validate date accuracy, only format). |
dateISO() | Boolean | Validates ISO date format. |
dateDE() | Boolean | Validates German date format (e.g., 29.04.1994 or 1.1.2006). |
number() | Boolean | Validates decimal numbers (including decimals). |
digits() | Boolean | Validates integers. |
creditcard() | Boolean | Validates credit card numbers. |
accept(extension) | Boolean | Validates strings with the same suffix. |
equalTo(other) | Boolean | Validates that two input fields have the same content. |
phoneUS() | Boolean | Validates US phone numbers. |
validate() Options
Description | Code | ||
---|---|---|---|
debug: Enables debug mode (form does not submit). | $(".selector").validate({ debug: true }) |
||
Sets debug mode as default. | $.validator.setDefaults({ debug: true }) |
||
submitHandler: Function to run after validation passes, includes form submission function, otherwise the form will not submit. | $(".selector").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } }) |
||
ignore: Excludes certain elements from validation. | $("#myform").validate({ ignore: ".ignore" }) |
||
rules: Custom rules, key:value format, key is the element to validate, value can be a string or object. | $(".selector").validate({ rules: { name: "required", email: { required: true, email: true } } }) |
||
messages: Custom error messages, key:value format, key is the element to validate, value can be a string or function. | $(".selector").validate({ rules: { name: "required", email: { required: true, email: true } }, messages: { name: "Name cannot be empty", email: { required: "E-mail cannot be empty", email: "Incorrect E-mail address" } } }) |
||
groups: Validation for a group of elements, uses a single error message, errorPlacement controls where the error message is placed. | `$("#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 })` | |
OnSubmit: Boolean, default true, specifies whether to validate on form submission. | $(".selector").validate({ onsubmit: false }) |
||
onfocusout: Boolean, default true, specifies whether to validate on focus out. | $(".selector").validate({ onfocusout: false }) |
||
onkeyup: Boolean, default true, specifies whether to validate on key press. | $(".selector").validate({ onkeyup: false }) |
||
onclick: Boolean, default true, specifies whether to validate on mouse click (typically for checkboxes and radio buttons). | $(".selector").validate({ onclick: false }) |
||
focusInvalid: Boolean, default true. After form submission, focuses on the first invalid element or the element that had focus before submission. | $(".selector").validate({ focusInvalid: false }) |
||
focusCleanup: Boolean, default false. Removes error message when an invalid element gains focus (avoid using with focusInvalid). | $(".selector").validate({ focusCleanup: true }) |
||
errorClass: String, default "error". Specifies the CSS class name for error messages, allows customizing error message styles. | $(".selector").validate({ errorClass: "invalid" }) |
||
errorElement: String, default "label". Specifies what tag to use for marking errors. | $(".selector").validate({ errorElement: "em" }) |
||
wrapper: String, specifies what tag to wrap the errorElement with. | $(".selector").validate({ wrapper: "li" }) |
||
errorLabelContainer: Selector, groups error messages into a single container. | $("#myform").validate({ errorLabelContainer: "#messageBox", wrapper: "li", submitHandler: function() { alert("Submitted!") } }) |
||
showErrors: Function to display the total number of invalid elements. | $(".selector").validate({ showErrors: function(errorMap, errorList) { $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors, see details below."); this.defaultShowErrors(); } }) |
||
errorPlacement: Function to customize where errors are placed. | $("#myform").validate({ errorPlacement: function(error, element) { error.appendTo(element.parent("td").next("td")); }, debug: true }) |
||
success: Action after an element passes validation, can be a CSS class or a function. | $("#myform").validate({ success: "valid", submitHandler: function() { alert("Submitted!") } }) |
addMethod(name, method, message) Method
The parameter name
is the name of the method being added.
The parameter method
is a function that takes three arguments: (value, element, param)
.
We can use addMethod
to add validation methods beyond the built-in Validation methods. For example, if there is a field that can only accept a single letter within the range a-f, the implementation would look like this:
$.validator.addMethod("af", function(value, element, params) {
if (value.length > 1) {
return false;
}
if (value >= params[0] && value <= params[1]) {
return true;
} else {
return false;
}
}, "Must be a single letter, a-f");
If there is a form field with name="username"
, then in the rules
, it would be written as:
username: {
af: ["a", "f"]
}
The first parameter of addMethod
is the name of the validation method being added, in this case, af
.
If there is only one parameter, it is written directly, such as af: "a"
, where a
is the sole parameter. If there are multiple parameters, they are enclosed in square brackets []
and separated by commas.
meta String Approach
$("#myform").validate({
meta: "validate",
submitHandler: function() {
alert("Submitted!")
}
});
<script type="text/javascript" src="js/jquery.metadata.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<form id="myform">
<input type="text" name="email" class="{validate: { required: true, email: true }}" />
<input type="submit" value="Submit" />
</form>
Example Demonstrations
Fictional Examples
- Error Message Container
- Custom Messages as Element Data
- Radio Buttons, Checkboxes, and Select Boxes
- Interaction with Form Plugin (AJAX Submission)
- Custom Methods and Message Display
- Dynamic Forms
- Using jQuery UI Themeroller for Form Styling
- TinyMCE - A Lightweight Browser-Based WYSIWYG Editor
- File Input Field
- jQuery Mobile Form Validation
Real-World Examples
- Milk Registration Form
- Marketo Registration Form
- House Buying/Selling Accordion Form
- Remote CAPTCHA Validation