參看:http://docs.jquery.com/Plugins/Validation並整理
jquery.validate.js是jquery旗下的一個驗證框架,借助jquery的優勢,我們可以迅速驗證一些常見的輸入,並且可以自己擴充自己的驗證方法,並且對國際化也有很好的支持
使用這個函數很簡單,看以下的代碼
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <scriptsrc="http://code.jquery.com/jquery-latest.js"></script>
- <linkrel="stylesheet"href="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.css"type="text/css"media="screen"/>
- <scripttype="text/javascript"src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
- <styletype="text/css">
- * { font-family: Verdana; font-size: 96%; }
- label { width: 10em; float: left; }
- label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
- p { clear: both; }
- .submit { margin-left: 12em; }
- em { font-weight: bold; padding-right: 1em; vertical-align: top; }
- </style>
- <script>
- $(document).ready(function(){
- $("#commentForm").validate();
- });
- </script>
- </head>
- <body>
- <formclass="cmxform"id="commentForm"method="get"action="">
- <fieldset>
- <legend>A simple comment form with submit validation and default messages</legend>
- <p>
- <labelfor="cname">Name</label>
- <em>*</em><inputid="cname"name="name"size="25"class="required"minlength="2"/>
- </p>
- <p>
- <labelfor="cemail">E-Mail</label>
- <em>*</em><inputid="cemail"name="email"size="25" class="required email"/>
- </p>
- <p>
- <labelfor="curl">URL</label>
- <em> </em><inputid="curl"name="url"size="25" class="url"value=""/>
- </p>
- <p>
- <labelfor="ccomment">Your comment</label>
- <em>*</em><textareaid="ccomment"name="comment"cols="22" class="required"></textarea>
- </p>
- <p>
- <inputclass="submit"type="submit"value="Submit"/>
- </p>
- </fieldset>
- </form>
- </body>
- </html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.css" type="text/css" media="screen" /> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <style type="text/css"> * { font-family: Verdana; font-size: 96%; } label { width: 10em; float: left; } label.error { float: none; color: red; padding-left: .5em; vertical-align: top; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } </style> <script> $(document).ready(function(){ $("#commentForm").validate(); }); </script> </head> <body> <form class="cmxform" id="commentForm" method="get" action=""> <fieldset> <legend>A simple comment form with submit validation and default messages</legend> <p> <label for="cname">Name</label> <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" /> </p> <p> <label for="cemail">E-Mail</label> <em>*</em><input id="cemail" name="email" size="25" class="required email" /> </p> <p> <label for="curl">URL</label> <em> </em><input id="curl" name="url" size="25" class="url" value="" /> </p> <p> <label for="ccomment">Your comment</label> <em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea> </p> <p> <input class="submit" type="submit" value="Submit"/> </p> </fieldset> </form> </body> </html>
總結,我們只要在加入如下的JAVASCRIPT代碼,就可以把指定的FORM加上驗證
- $(document).ready(function(){
- $("#commentForm").validate();
- });
$(document).ready(function(){ $("#commentForm").validate(); });
不過我們還要在需要驗證的INPUT里面class加入required說明是必填項,其他的就是驗證相關數據比如email就是驗證email的數據結構
以下列出validate自帶的默認驗證
required: "必選字段",
remote: "請修正該字段",
email: "請輸入正確格式的電子郵件",
url: "請輸入合法的網址",
date: "請輸入合法的日期",
dateISO: "請輸入合法的日期 (ISO).",
number: "請輸入合法的數字",
digits: "只能輸入整數",
creditcard: "請輸入合法的信用卡號",
equalTo: "請再次輸入相同的值",
accept: "請輸入擁有合法后綴名的字符串",
maxlength: jQuery.format("請輸入一個長度最多是 {0} 的字符串"),
minlength: jQuery.format("請輸入一個長度最少是 {0} 的字符串"),
rangelength: jQuery.format("請輸入一個長度介於 {0} 和 {1} 之間的字符串"),
range: jQuery.format("請輸入一個介於 {0} 和 {1} 之間的值"),
max: jQuery.format("請輸入一個最大為 {0} 的值"),
min: jQuery.format("請輸入一個最小為 {0} 的值")
validate ()的可選項
debug:進行調試模式
$(".selector").validate({ debug: true })
把調試設置為默認
$.validator.setDefaults({ debug: true })
submitHandler:用其他方式替代默認的SUBMIT,比如用AJAX的方式提交
$(".selector").validate({ submitHandler: function(form) {$(form).ajaxSubmit(); } })
ignore:忽略某些元素不驗證
$("#myform").validate({ ignore: ".ignore" })
rules: 默認下根據form的classes, attributes, metadata判斷,但也可以在validate函數里面聲明 Key/value 可自定義規則. Key是對象的名字 value是對象的規則,可以組合使用 class/attribute/metadata rules.
以下代碼特別驗證selector類中name='name'是必填項並且 email是既是必填又要符合email的格式
$(".selector").validate({ rules: { // simple rule, converted to {required:true} name: "required", // compound rule email: { required: true, email: true } } })
messages:更改默認的提示信息
$(".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" } } })
groups:定義一個組,把幾個地方的出錯信息同意放在一個地方,用errorPlacement控制把出錯信息放在哪里
$("#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 提交時驗證. 設置唯false就用其他方法去驗證 Code 不用onsubmit驗證,就允許用戶無論用什么方法去驗證,而是提交時, 用 keyup/blur/click 等方法.
$(".selector").validate({ onsubmit: false }) onfocusout Boolean Default: true Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid. Code Disables onblur validation.
$(".selector").validate({ onfocusout: false }) onkeyup Boolean Default: true 在keyup時驗證. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Code Disables onkeyup validation.
$(".selector").validate({ onkeyup: false }) onclick Boolean Default: true 在checkboxes 和 radio 點擊時驗證. Code Disables onclick validation of checkboxes and radio buttons.
$(".selector").validate({ onclick: false }) focusInvalid Boolean Default: true 把焦點聚焦在最后一個動作或者最近的一次出錯上via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off. Code Disables focusing of invalid elements.
$(".selector").validate ({ focusInvalid: false }) focusCleanup Boolean Default: false 如果是true那么刪除出錯類從出錯的元素上並且隱藏出錯信息當這個元素被聚焦 .避免和 focusInvalid.一起用 Code Enables cleanup when focusing elements, removing the error class and hiding error messages when an element is focused.
$(".selector").validate({ focusCleanup: true }) meta String 為了元數據使用其他插件你要包裝 你的驗證規則 在他們自己的項目中可以用這個特殊的選項 Tell the validation plugin to look inside a validate-property in metadata for validation rules.
$("#myform").validate({ meta: "validate", submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ meta: "validate", submitHandler: function() { alert("Submitted!") } }) }); </script> </head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.metadata.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <form id="myform"> <input type="text" name="email" class="{validate:{ required: true, email:true }}" /> <br/> <input type="submit" value="Submit" /> </form> </body> </html> errorClass String Default: "error" 創建錯誤類的名字為了去尋找存在的錯誤標簽和增加它到驗證失敗的元素中去。 Code Sets the error class to "invalid".
$(".selector").validate({ errorClass: "invalid" }) errorElement String Default: "label" 設置錯誤的元素,默認的是label你可以改成em.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). Code Sets the error element to "em".
$(".selector").validate({ errorElement: "em" }) wrapper String 在出錯信息外用其他的元素包裝一層。Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages. Code Wrap each error element with a list item, useful when using an ordered or unordered list as the error container.
$(".selector").validate({ wrapper: "li" }) errorLabelContainer 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!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ errorLabelContainer: "#messageBox", wrapper: "li", submitHandler: function() { alert("Submitted!") } }) }); </script> </head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <ul id="messageBox"></ul> <form id="myform" action="/login" method="post"> <label>Firstname</label> <input name="fname" class="required" /> <label>Lastname</label> <input name="lname" title="Your lastname, please!" class="required" /> <br/> <input type="submit" value="Submit"/> </form> </body> </html> errorContainer Selector 顯示或者隱藏驗證信息 使用一個額外的容器去顯示錯誤信息
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!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ errorContainer: "#messageBox1, #messageBox2", errorLabelContainer: "#messageBox1 ul", wrapper: "li", debug:true, submitHandler: function() { alert("Submitted!") } }) }); </script> <style>#messageBox1, #messageBox2 { display: none }</style> </head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <div id="messageBox1"> <ul></ul> </div> <form id="myform" action="/login" method="post"> <label>Firstname</label> <input name="fname" class="required" /> <label>Lastname</label> <input name="lname" title="Your lastname, please!" class="required" /> <br/> <input type="submit" value="Submit"/> </form> <div id="messageBox2"> <h3>There are errors in your form, see details above!</h3> </div> </body> </html> showErrors Callback Default: None, uses built-in message disply. 得到錯誤的顯示句柄
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(). Code 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(); } }) errorPlacement Callback Default: 把錯誤label放在驗證的元素后面 可選錯誤label的放置位置. 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 }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ errorPlacement: function(error, element) { error.appendTo( element.parent("td").next("td") ); }, debug:true }) }); </script> </head> <body> <form id="myform" action="/login" method="post"> <table> <tr> <td><label>Firstname</label> <td><input name="fname" class="required" value="Pete" /></td> <td></td> </tr> <tr> <td><label>Lastname</label></td> <td><input name="lname" title="Your lastname, please!" class="required" /></td> <td></td> </tr> <tr> <td></td><td><input type="submit" value="Submit"/></td><td></td> </table> </form> </body> </html> success String , Callback 成功時的class.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. That can be used to add a text like "ok!". 添加"valid" 到驗證驗證元素, 在CSS中定義的樣式
$("#myform").validate({ success: "valid", submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ success: "valid", submitHandler: function() { alert("Submitted!") } }) }); </script> <style>label.valid { background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat; height:16px; width:16px; display: block; position: absolute; top: 4px; left: 152px; }</style> </head> <body> <form id="myform"> <input type="text" name="email" class="required" /> <br/> <input type="submit" value="Submit" /> </form> </body> </html> 添加"valid" 到驗證驗證元素, 在CSS中定義的樣式,並加入“ok”的文字 $("#myform").validate({ success: function(label) { label.addClass("valid").text("Ok!") }, submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ success: function(label) { label.addClass("valid").text("Ok!") }, submitHandler: function() { alert("Submitted!") } }) }); </script> <style>label.valid { background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat; height:16px; width:16px; display: block; position: absolute; top: 4px; left: 152px; padding-left: 18px; }</style> </head> <body> <form id="myform"> <input type="text" name="email" class="required" /> <br/> <input type="submit" value="Submit" /> </form> </body> </html> highlight Callback Default: Adds errorClass (see the option) to the Element 高亮顯示錯誤信息。 或者說重寫出錯時的出錯元素的顯示。Override to decide which fields and how to highlight. Code Highlights an invalid element by fading it out and in again.
$(".selector").validate({ highlight: function(element, errorClass) { $(element).fadeOut(function() { $(element).fadeIn() }) } }) Code Adds the error class to both the invalid element and it's label
$(".selector").validate({ highlight: function(element, errorClass) { $(element).addClass(errorClass); $(element.form).find("label[for=" + element.id + "]").addClass(errorClass); }, unhighlight: function(element, errorClass) { $(element).removeClass(errorClass); $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass); } });
Name | Type |
---|---|
validate( options ) | Returns: Validator |
驗證所選的FORM | |
valid( ) | Returns: Boolean |
檢查是否驗證通過 | |
rules( ) | Returns: Options |
返回元素的驗證規則 | |
rules( "add", rules ) | Returns: Options |
增加驗證規則。 | |
rules( "remove", rules ) | Returns: Options |
刪除驗證規則 | |
removeAttrs( attributes ) | Returns: Options |
刪除特殊屬性並且返回他們 |
Custom selectors
Utilities
Validator
validate方法返回一個Validator對象, 它有很多方法, 讓你能使用引發校驗程序或者改變form的內容. validator對象有很多方法, 但下面只是列出常用的.
There are a few static methods on the validator object:
List of built-in Validation methods
A set of standard validation methods is provided:
Name | Type |
---|---|
phoneUS( ) | Returns: Boolean |
驗證美式的電話號碼 |

jQuery.validator.addMethod("mobile", function (value, element) {
var length = value.length;
var phone = /^0\d{2,4}-?\d{7,8}$/ //驗證固定電話
var mobile = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/; //驗證手機
return this.optional(element) || (length == 11 && phone.test(value) || (length == 11 && mobile.test(value)));
}, "電話或手機號碼格式錯誤!");
jQuery.validator.addMethod("certCheck", function (value, element) {
var length = value.length;
if (length > 0) {
var certNo = /^(\d{6})(18|19|20)?(\d{2})([01]\d)([0123]\d)(\d{3})(\d|X|x)?$/; //身份證號碼
return this.optional(element) || (length == 18 && certNo.test(value));
}
else {
return true;
}
}, "身份證號碼格式錯誤!");
$(function () {
$("#addForm").validate({
submitHandler: function (form) {
form.submit();
},
rules: {
ContactName: { required: true },
ContactIdno: { certCheck: true },
ContactTel: { required: true, mobile: true }
},
messages: {
ContactName: { required: "請輸入聯系人姓名!" }, ContactIdno: { certCheck: "請輸入正確的身份證號碼!" },
ContactTel: { required: "請輸入聯系電話!", mobile: "請輸入正確的電話號碼!" }
}
});
});