jQuery Validate
jQuery Validate
The jQuery Validate plug-in provides powerful validation functions for forms, making client-side form validation easier and providing a large number of Customization options to meet various application needs. The plugin bundles a set of useful validation methods, including URL and email validation, and provides an API for writing user-defined methods. All bundled methods use English for error messages by default and have been translated into 37 other languages.
This plugin is written and maintained by J?rn Zaefferer, a member of the jQuery team, a lead developer on the jQuery UI team, and the maintainer of QUnit. This plugin has been around since 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 and download the latest version of the jQuery Validate plug-in.
Import js library
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
Default verification rules
Serial number | Rules | Description |
---|---|---|
1 | required:true | Required fields. |
2 | remote:"check.php" | Use the ajax method to call check.php to verify the input value. |
3 | email:true | A correctly formatted email must be entered. |
4 | url:true | You must enter the URL in the correct format. |
5 | date:true | The date must be entered in the correct format. Date verification ie6 error, use with caution. |
6 | dateISO:true | The date (ISO) in the correct format must be entered, for example: 2009-06-23, 1998/01/ twenty two. Only the format is verified, not the validity. |
7 | number:true | Must enter a legal number (negative number, decimal). |
8 | digits:true | Must enter an integer. |
9 | creditcard: | Must enter a legal credit card number. |
10 | equalTo:"#field" | The input value must be the same as #field. |
11 | accept: | Enter a string with a legal suffix (the suffix of the uploaded file). |
12 | maxlength:5 | Enter a string with a maximum length of 5 (Chinese characters count as one character). |
13 | minlength:10 | Enter a string with a minimum length of 10 (Chinese characters count as one character). |
14 | rangelength:[5,10] | The input length must be between 5 and 10 (Chinese characters count as one character ). |
15 | range:[5,10] | The input value must be between 5 and 10. |
16 | max:5 | The input value cannot be greater than 5. |
17 | min:10 | The input value cannot be less than 10. |
Default prompt
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 message prompt package, which is located in dist/localization/messages_zh.js of the download package. The content is as follows:
(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: "請輸入有效的網(wǎng)址", date: "請輸入有效的日期", dateISO: "請輸入有效的日期 (YYYY-MM-DD)", number: "請輸入有效的數(shù)字", digits: "只能輸入數(shù)字", creditcard: "請輸入有效的信用卡號碼", equalTo: "你的輸入不相同", extension: "請輸入有效的后綴", maxlength: $.validator.format("最多可以輸入 {0} 個字符"), minlength: $.validator.format("最少要輸入 {0} 個字符"), rangelength: $.validator.format("請輸入長度在 {0} 到 {1} 之間的字符串"), range: $.validator.format("請輸入范圍在 {0} 到 {1} 之間的數(shù)值"), max: $.validator.format("請輸入不大于 {0} 的數(shù)值"), min: $.validator.format("請輸入不小于 {0} 的數(shù)值")});}));
You can localize the message The file dist/localization/messages_zh.js is introduced to the page:
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
Usage method
1. Write the verification rules into the control
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文網(wǎng)(php.cn)</title> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().ready(function() { $("#commentForm").validate(); }); </script> <style> .error{ color:red; } </style> </head> <body> <form class="cmxform" id="commentForm" method="get" action=""> <fieldset> <legend>輸入您的名字,郵箱,URL,備注。</legend> <p> <label for="cname">Name (必需, 最小兩個字母)</label> <input id="cname" name="name" minlength="2" type="text" required> </p> <p> <label for="cemail">E-Mail (必需)</label> <input id="cemail" type="email" name="email" required> </p> <p> <label for="curl">URL (可選)</label> <input id="curl" type="url" name="url"> </p> <p> <label for="ccomment">備注 (必需)</label> <textarea id="ccomment" name="comment" required></textarea> </p> <p> <input class="submit" type="submit" value="Submit"> </p> </fieldset> </form> </body> </html>
Try it
2. Write the verification rules into the js code at
$().ready(function() {// 在鍵盤按下并釋放及提交后驗證提交表單 $("#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: "請輸入您的名字", lastname: "請輸入您的姓氏", username: { required: "請輸入用戶名", minlength: "用戶名必需由兩個字母組成" }, password: { required: "請輸入密碼", minlength: "密碼長度不能小于 5 個字母" }, confirm_password: { required: "請輸入密碼", minlength: "密碼長度不能小于 5 個字母", equalTo: "兩次密碼輸入不一致" }, email: "請輸入一個正確的郵箱", agree: "請接受我們的聲明", topic: "請選擇兩個主題" }});
messages. If a control does not have a message, the default message will be called
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文網(wǎng)(php.cn)</title> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().ready(function() { // 在鍵盤按下并釋放及提交后驗證提交表單 $("#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: "請輸入您的名字", lastname: "請輸入您的姓氏", username: { required: "請輸入用戶名", minlength: "用戶名必需由兩個字母組成" }, password: { required: "請輸入密碼", minlength: "密碼長度不能小于 5 個字母" }, confirm_password: { required: "請輸入密碼", minlength: "密碼長度不能小于 5 個字母", equalTo: "兩次密碼輸入不一致" }, email: "請輸入一個正確的郵箱", agree: "請接受我們的聲明", topic: "請選擇兩個主題" } }); }); </script> <style> .error{ color:red; } </style> </head> <body> <form class="cmxform" id="signupForm" method="get" action=""> <fieldset> <legend>驗證完整的表單</legend> <p> <label for="firstname">名字</label> <input id="firstname" name="firstname" type="text"> </p> <p> <label for="lastname">姓氏</label> <input id="lastname" name="lastname" type="text"> </p> <p> <label for="username">用戶名</label> <input id="username" name="username" type="text"> </p> <p> <label for="password">密碼</label> <input id="password" name="password" type="password"> </p> <p> <label for="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">請同意我們的聲明</label> <input type="checkbox" class="checkbox" id="agree" name="agree"> </p> <p> <label for="newsletter">我樂意接收新信息</label> <input type="checkbox" class="checkbox" id="newsletter" name="newsletter"> </p> <fieldset id="newsletter_topics"> <legend>主題 (至少選擇兩個) - 注意:如果沒有勾選“我樂意接收新信息”以下選項會隱藏,但我們這里作為演示讓它可見</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" style="display:none">至少選擇兩個</label> </fieldset> <p> <input class="submit" type="submit" value="提交"> </p> </fieldset> </form> </body> </html>
Try it
required: true The value is required.
required: "#aa:checked" If the value of the expression is true, verification is required.
required: function(){} Returns true, indicating that verification is required.
The latter two are commonly used for elements in the form that need to be filled in or left out at the same time.
Common methods and issues to note
1. Use other methods to replace the default SUBMIT
$().ready(function() { $("#signupForm").validate({ submitHandler:function(form){ alert("提交事件!"); form.submit(); } });});
Use ajax method
$(".selector").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } })
You can set the default value of validate. The writing is as follows:
$.validator.setDefaults({ submitHandler: function(form) { alert("提交事件!");form.submit(); }});
If you want to submit the form, you need to use form.submit() instead of $(form).submit().
2. Debug, only verify and not submit the form
If this parameter is true, the form will not be submitted and only checked, which is very convenient during debugging.
$().ready(function() { $("#signupForm").validate({ debug:true });});
If there are multiple forms on a page that you want to set as debug, use:
$.validator.setDefaults({ debug: true})
3, ignore: ignore certain elements and do not verify
ignore: ".ignore"
4, Change the position where the error message is displayed
errorPlacement:Callback
Indicate the position where the error is placed. The default is: error.appendTo(element.parent()); that is, the error message is placed behind the verified element.
errorPlacement: function(error, element) { error.appendTo(element.parent()); }
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文網(wǎng)(php.cn)</title> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().ready(function() { // 提交時驗證表單 var validator = $("#form1").validate({ errorPlacement: function(error, element) { // Append error within linked label $( element ) .closest( "form" ) .find( "label[for='" + element.attr( "id" ) + "']" ) .append( error ); }, errorElement: "span", messages: { user: { required: " (必需字段)", minlength: " (不能少于 3 個字母)" }, password: { required: " (必需字段)", minlength: " (字母不能少于 5 個且不能大于 12 個)", maxlength: " (字母不能少于 5 個且不能大于 12 個)" } } }); $(".cancel").click(function() { validator.resetForm(); }); }); </script> <style> .error{ color:red; } </style> </head> <body> <form method="get" class="cmxform" id="form1" action=""> <fieldset> <legend>登錄框</legend> <p> <label for="user">用戶名</label> <input id="user" name="user" required minlength="3"> </p> <p> <label for="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> </body> </html>
Try it
The function of the code is: Under normal circumstances, the error message is displayed in < td class="status"></td>, if it is radio, it will be displayed in <td></td>, if it is checkbox, it will be displayed behind the content.
Parameters | Type | Description | Default value |
---|---|---|---|
String | Specifies the css class name of the error prompt, and you can customize the style of the error prompt. | "error" | |
String | What label should be used to mark errors? The default is label, which can be changed to em. | "label" | |
Selector | Display or hide the verification information, which can automatically realize when an error message appears. The container properties become displayed and hidden when there are no errors, which is of little use. | errorContainer: "#messageBox1, #messageBox2" | |
Selector | Put the error message Put them uniformly in a container. | ||
String | What label should be used to wrap the errorELement above. |
Trigger method | Type | Description | Default value |
---|---|---|---|
onsubmit | Boolean | Validate on submission. Set to false to use other methods to verify. | true |
onfocusout | Boolean | Validate when focus is lost (excluding checkboxes/radio buttons). | true |
onkeyup | Boolean | Validate on keyup. | true |
onclick | Boolean | Validates on click of checkboxes and radio buttons. | true |
focusInvalid | Boolean | After submitting the form, the form that failed validation (the first one or obtained before submission The focused (unvalidated) form will gain focus. | true |
focusCleanup | Boolean | If true then remove errors when an element that fails validation gets focus hint. Avoid using it with focusInvalid. | false |
// 重置表單$().ready(function() { var validator = $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); $("#reset").click(function() { validator.resetForm(); });});
8. Asynchronous verification
remote:URL
Use ajax for verification. By default, the current verified value will be submitted to the remote address. If you need to submit other values, you can use the data option.
remote: "check-email.php"
remote: { url: "check-email.php", //后臺處理程序 type: "post", //數(shù)據(jù)發(fā)送方式 dataType: "json", //接受數(shù)據(jù)格式 data: { //要傳遞的數(shù)據(jù) username: function() { return $("#username").val(); } }}
The remote address can only output "true" or "false" and no other output.
9. Add custom verification
addMethod:name, method, message
Custom verification method
// 中文字兩個字節(jié)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("請確保輸入的值在{0}-{1}個字節(jié)之間(一個中文字算2個字節(jié))"));// 郵政編碼驗證 jQuery.validator.addMethod("isZipCode", function(value, element) { var tel = /^[0-9]{6}$/; return this.optional(element) || (tel.test(value));}, "請正確填寫您的郵政編碼");
Note: To add or Add in jquery.validate.js file. It is recommended to write it in the additional-methods.js file.
Note: Add: isZipCode: "can only include Chinese characters, English letters, numbers and underlines" in the messages_cn.js file. Add a reference to the additional-methods.js file before calling.
10. Verification of radio, checkbox, and select
The required of radio means that 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"/>
The required in checkbox means it must be selected.
<input type="checkbox" class="checkbox" id="agree" name="agree" required />
The minlength of checkbox represents the minimum number that must be selected, maxlength represents the maximum number of selections, and rangelength:[2,3] represents the range of the number of selections.
<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's required indicates that 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's minlength represents the minimum number of selected items (multi-selectable select), maxlength represents the maximum selected number, and rangelength:[2,3] represents the selected number interval.
<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 whether the verification is passed. |
rules() | Options | Returns the validation rules of the element. |
rules("add",rules) | Options | Add verification rules. |
rules("remove",rules) | Options | Remove validation rules. |
removeAttrs(attributes) | Options | Remove special attributes and return them. |
Custom Selector | ||
:blank | Validator | Filter with no value. |
:filled | Array <Element> | Filter with value. |
:unchecked | Array <Element> | Filter for unselected elements. |
Utilities | ||
jQuery.format(template,argument,argumentN...) | String | Replace {n} in the template with parameters. |
Validator
validate method returns a Validator object. The Validator object has many methods that can be used to trigger the validation program or change the content of the form. Here are some commonly used methods.
Name | Return type | Description |
---|---|---|
form() | Boolean | Verify whether the form returns success or failure. |
element(element) | Boolean | Verifies whether a single element succeeds or fails. |
resetForm() | undefined | Restore the previously verified FORM to its original state before verification. |
showErrors(errors) | undefined | Show specific error messages. |
Validator function | ||
setDefaults(defaults) | undefined | Change the default settings. |
addMethod(name,method,message) | undefined | Add a new verification method. Must include a unique name, a JAVASCRIPT method and a default message. |
addClassRules(name,rules) | undefined | Add a combined verification type, which is more useful when using multiple verification methods in a class. |
addClassRules(rules) | undefined | Add a combined verification type, which is more useful when using multiple verification methods in a class. This is to add multiple verification methods at the same time. |
Built-in verification method
Name | Return type | Description |
---|---|---|
required () | Boolean | Required validation element. |
required(dependency-expression) | Boolean | Required elements depend on the result of expression. |
required(dependency-callback) | Boolean | Required elements depend on the result of the callback function. |
remote(url) | Boolean | Request remote verification. url is usually a remote call method. |
minlength(length) | Boolean | Set the minimum length. |
maxlength(length) | Boolean | Set the maximum length. |
rangelength(range) | Boolean | Set a length range [min,max]. |
min(value) | Boolean | Set the minimum value. |
max(value) | Boolean | Set the maximum value. |
email() | Boolean | Verify the email format. |
range(range) | Boolean | Set the range of values. |
url() | Boolean | Verify URL format. |
date() | Boolean | Verify the date format (similar to the format of 30/30/2008, the date accuracy is not verified, only the format is verified) . |
dateISO() | Boolean | Verify the ISO type date format. |
dateDE() | Boolean | Verifies the German date format (29.04.1994 or 1.1.2006). |
number() | Boolean | Validate decimal numbers (including decimals). |
digits() | Boolean | Validate integers. |
creditcard() | Boolean | Verify credit card number. |
accept(extension) | Boolean | Verify strings with the same suffix name. |
equalTo(other) | Boolean | Verify whether the contents of the two input boxes are the same. |
phoneUS() | Boolean | Verify the US phone number. |
validate() options
Code | |
---|---|