目錄
List of built-in Validation methods9
轉自http://www.cnblogs.com/buzzlight/archive/2010/06/30/1768364.html
jquery.validate使用攻略
第一章 jquery.validate使用攻略
好幾年不寫JS了,資料整理起來比較慢,格式也有點亂
主要分幾部分
jquery.validate 基本用法
jquery.validate API說明
jquery.validate 自定義
jquery.validate 常見類型的驗證代碼
下載地址
jquery.validate插件的文檔地址
http://docs.jquery.com/Plugins/Validation
jquery.validate插件的主頁
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
jquery.validate插件主頁上提供的demo
http://jquery.bassistance.de/validate/demo/
驗證規則
下面是默認校驗規則,也可以自定義規則
(1)required:true 必輸字段
(2)remote:"check.php" 使用ajax方法調用check.php驗證輸入值
(3)email:true 必須輸入正確格式的電子郵件
(4)url:true 必須輸入正確格式的網址
(5)date:true 必須輸入正確格式的日期
(6)dateISO:true 必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22 只驗證格式,不驗證有效性
(7)number:true 必須輸入合法的數字(負數,小數)
(8)digits:true 必須輸入整數
(9)creditcard: 必須輸入合法的信用卡號
(10)equalTo:"#field" 輸入值必須和#field相同
(11)accept: 輸入擁有合法后綴名的字符串(上傳文件的后綴)
(12)maxlength:5 輸入長度最多是5的字符串(漢字算一個字符)
(13)minlength:10 輸入長度最小是10的字符串(漢字算一個字符)
(14)rangelength:[5,10] 輸入長度必須介於 5 和 10 之間的字符串")(漢字算一個字符)
(15)range:[5,10] 輸入值必須介於 5 和 10 之間
(16)max:5 輸入值不能大於5
(17)min:10 輸入值不能小於10
驗證提示
下面是默認的驗證提示,官網有簡體中文版的驗證提示下載,或者通過jQuery.extend(jQuery.validator.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.",
accept: "Please enter a value with a valid extension.",
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}.")
使用方式
1:
在控件中使用默認驗證規則,例子:
電子郵件(必填)
<input id="email" class="required email" value="email@" />
2:
可以在控件中自定義驗證規則,例子:
自定義(必填,[3,5])
<input id="complex" value="hi" class="{required:true,minlength:3, maxlength:5,
messages:{required:'為什么不輸入一點文字呢',minlength:'輸入的太少了',maxlength:'輸入那么多干嘛'}}" />
3:
通過javascript自定義驗證規則,下面的JS自定義了兩個規則,password和confirm_password
$().ready(function() {
$("#form2").validate({
rules: {
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
}
},
messages: {
password: {
required: "沒有填寫密碼",
minlength: jQuery.format("密碼不能小於{0}個字符")
},
confirm_password: {
required: "沒有確認密碼",
minlength: "確認密碼不能小於{0}個字符",
equalTo: "兩次輸入密碼不一致嘛"
}
}
});
});
required除了設置為true/false之外,還可以使用表達式或者函數,比如
$("#form2").validate({
rules: {
funcvalidate: {
required: function() {return $("#password").val()!=""; }
}
},
messages: {
funcvalidate: {
required: "有密碼的情況下必填"
}
}
});
Html
密碼<input id="password" name="password" type="password" />
確認密碼<input id="confirm_password" name="confirm_password" type="password" />
條件驗證<input id="funcvalidate" name="funcvalidate" value="" />
4:
使用meta自定義驗證信息
首先用JS設置meta
$("#form3").validate({ meta: "validate" });
Html
email<input class="{validate:{required:true, email:true,
messages:{required:'輸入email地址', email:'你輸入的不是有效的郵件地址'}}}"/>
5:
使用meta可以將驗證規則寫在自定義的標簽內,比如validate
JS設置meta
$().ready(function() {
$.metadata.setType("attr", "validate");
$("#form1").validate();
});
Html
<input id="email" name="email"
validate="{required:true, email:true, messages:{required:'輸入email地址', email:'你輸入的不是有效的郵件地址'}}" />
6:
自定義驗證規則
對於復雜的驗證,可以通過jQuery.validator.addMethod添加自定義的驗證規則
官網提供的additional-methods.js里包含一些常用的驗證方式,比如lettersonly,ziprange,nowhitespace等
例子
// 字符驗證
jQuery.validator.addMethod("userName", function(value, element) {
return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
}, "用戶名只能包括中文字、英文字母、數字和下划線");
//然后就可以使用這個規則了
$("#form1").validate({
// 驗證規則
rules: {
userName: {
required: true,
userName: true,
rangelength: [5,10]
}
},
/* 設置錯誤信息 */
messages: {
userName: {
required: "請填寫用戶名",
rangelength: "用戶名必須在5-10個字符之間"
}
},
});
7:
radio、checkbox、select的驗證方式類似
radio的驗證
性別
<span>
男<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}"/><br />
女<input type="radio" id="gender_female" value="f" name="gender" />
</span>
checkbox的驗證
最少選擇兩項
<span>
選項1<input type="checkbox" id="check_1" value="1" name="checkGroup"
class="{required:true,minlength:2, messages:{required:'必須選擇',minlength:'至少選擇2項'}}" /><br />
選項2<input type="checkbox" id="check_2" value="2" name="checkGroup" /><br />
選項3<input type="checkbox" id="check_3" value="3" name="checkGroup" /><br />
</span>
select的驗證
下拉框
<span>
<select id="selectbox" name="selectbox" class="{required:true}">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</span>
8:
Ajax驗證
用remote可以進行Ajax驗證
remote: {
url: "url", //url地址
type: "post", //發送方式
dataType: "json", //數據格式 data: { //要傳遞的數據
username: function() {
return $("#username").val();
}}
}
補充: jQuery Validation插件remote驗證方式的Bug
http://www.cnblogs.com/JeffreyZhao/archive/2009/12/04/jquery-validate-remote-bug.html
第二章 jQuery.validate.js API
| Name |
Type |
| Returns: Validator |
|
| 驗證所選的FORM |
|
| Returns: Boolean |
|
| 檢查是否驗證通過 |
|
| Returns: Options |
|
| 返回元素的驗證規則 |
|
| Returns: Options |
|
| 增加驗證規則。 |
|
| Returns: Options |
|
| 刪除驗證規則 |
|
| Returns: Options |
|
| 刪除特殊屬性並且返回他們 |
|
Custom selectors
| Name |
Type |
Custom selectors:
| Name |
Type |
| 沒有值的篩選器 |
|
| 有值的篩選器 |
|
| 沒選擇的元素的篩選器 |
|
Utilities
| Name |
Type |
String utilities:
| Name |
Type |
| Returns: String |
|
| 用參數代替模板中的 {n}。 |
|
Validator
validate方法返回一個Validator對象, 它有很多方法, 讓你能使用引發校驗程序或者改變form的內容. validator對象有很多方法, 但下面只是列出常用的.
| Name |
Type |
Validator methods:
| Name |
Type |
| Returns: Boolean |
|
| 驗證form返回成功還是失敗 |
|
| Returns: Boolean |
|
| 驗證單個元素是成功還是失敗 |
|
| Returns: undefined |
|
| 把前面驗證的FORM恢復到驗證前原來的狀態 |
|
| Returns: undefined |
|
| 顯示特定的錯誤信息 |
|
There are a few static methods on the validator object:
| Name |
Type |
Validator functions:
| Name |
Type |
| Returns: undefined |
|
| 改變默認的設置 |
|
| Returns: undefined |
|
| 添加一個新的驗證方法. 必須包括一個獨一無二的名字,一個JAVASCRIPT的方法和一個默認的信息 |
|
| Returns: undefined |
|
| 增加組合驗證類型 在一個類里面用多種驗證方法里比較有用 |
|
| Returns: undefined |
|
| 增加組合驗證類型 在一個類里面用多種驗證方法里比較有用,這個是一下子加多個 |
|
[edit ]
List of built-in Validation methods
A set of standard validation methods is provided:
| Name |
Type |
Methods:
| Name |
Type |
| Returns: Boolean |
|
| 必填驗證元素 |
|
| Returns: Boolean |
|
| 必填元素依賴於表達式的結果. |
|
| Returns: Boolean |
|
| 必填元素依賴於回調函數的結果. |
|
| Returns: Boolean |
|
| 請求遠程校驗。url通常是一個遠程調用方法 |
|
| Returns: Boolean |
|
| 設置最小長度 |
|
| Returns: Boolean |
|
| 設置最大長度 |
|
| Returns: Boolean |
|
| 設置一個長度范圍[min,max] |
|
| Returns: Boolean |
|
| 設置最小值. |
|
| Returns: Boolean |
|
| 設置最大值. |
|
| Returns: Boolean |
|
| 設置值的范圍 |
|
| Returns: Boolean |
|
| 驗證電子郵箱格式 |
|
| Returns: Boolean |
|
| 驗證連接格式 |
|
| Returns: Boolean |
|
| 驗證日期格式(類似30/30/2008的格式,不驗證日期准確性只驗證格式) |
|
| Returns: Boolean |
|
| 研制ISO類型的日期格式 |
|
| Returns: Boolean |
|
| 驗證德式的日期格式(29.04.1994 or 1.1.2006) |
|
| Returns: Boolean |
|
| 驗證十進制數字(包括小數的) |
|
| Returns: Boolean |
|
| Makes the element require a decimal number with german format. |
|
| Returns: Boolean |
|
| 驗證整數 |
|
| Returns: Boolean |
|
| 驗證信用卡號 |
|
| Returns: Boolean |
|
| 驗證相同后綴名的字符串 |
|
| Returns: Boolean |
|
| 驗證兩個輸入框的內容是否相同 |
|
| Name |
Type |
| Returns: Boolean |
|
| 驗證美式的電話號碼 |
|
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:定義一個組,把幾個地方的出錯信息同意放在一個地方,用error Placement控制把出錯信息放在哪里
$("#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
})
| nsubmit |
Default: true |
|
| 提交時驗證. 設置唯false就用其他方法去驗證 |
||
| · Code 不用onsubmit驗證,就允許用戶無論用什么方法去驗證,而是提交時, 用 keyup/blur/click 等方法. $(".selector").validate({ onsubmit: false }) |
||
| onfocusout |
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 |
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 |
Default: true |
|
| 在checkboxes 和 radio 點擊時驗證. |
||
| · Code Disables onclick validation of checkboxes and radio buttons. $(".selector").validate({ onclick: false }) |
||
| focusInvalid |
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 |
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 |
|
|
| 為了元數據使用其他插件你要包裝 你的驗證規則 在他們自己的項目中可以用這個特殊的選項 |
||
| 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"> <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 |
Default: "error" |
|
| 創建錯誤類的名字為了去尋找存在的錯誤標簽和增加它到驗證失敗的元素中去。 |
||
| · Code Sets the error class to "invalid". $(".selector").validate({ errorClass: "invalid" }) |
||
| errorElement |
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 |
|
|
| 在出錯信息外用其他的元素包裝一層。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 |
|
|
| 把錯誤信息統一放在一個容器里面。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 |
|
|
| 顯示或者隱藏驗證信息 |
||
| 使用一個額外的容器去顯示錯誤信息 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"> <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 |
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 |
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"> <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 |
|
|
| 成功時的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"> <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"> <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 |
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); } }); |
||
| unhighlight |
Default: 默認是去掉error類 |
|
| Called to revert changes made by option highlight, same arguments as highlight. |
||
第三章 自定義jquery-validate的驗證行為
1: 自定義表單提交
設置submitHandler來自定義表單提交動作
$(".selector").validate({
submitHandler: function(form) { alert("驗證通過"); }
});
如果需要提交表單,可以調用
form.submit(); 或者$(form).ajaxSubmit();
2: 調試模式
將debug設置為true,表單不會提交,只進行檢查,方便調試
$(".selector").validate({
debug: true
})
3: 設置validate的默認值
使用setDefaults可以設置validate的默認值,比如默認所有表單驗證都是在debug模式下進行
$.validator.setDefaults({
debug: true
})
4: 某些元素不驗證
設置ignore屬性可以忽略某些元素不驗證
$(".selector").validate({
ignore: "ignore"
})
5: 驗證時機
jquery.validate可以很方便的設置在什么時候觸發驗證動作
onsubmit: 提交時是否驗證
$(".selector").validate({
onsubmit: false
})
onfocusout: 失去焦點時驗證(checkboxes/radio除外)
$(".selector").validate({
onfocusout: false
})
onkeyup: 在keyup時驗證
$(".selector").validate({
onkeyup: false
})
onclick: 在checkboxes、radio點擊時驗證.
$(".selector").validate({
onclick: false
})
6: 重寫驗證規則和驗證提示信息
//重寫max的的驗證提示信息
$.validator.messages.max = jQuery.format("Your totals musn't exceed {0}!");
//重寫equal方法
$.validator.methods.equal = function(value, element, param) {
return value == param;
};
7: focusInvalid 是否把焦點聚焦在最后一個動作或者最近的一次出錯上
$(".selector").validate({
focusInvalid: false
})
8: focusCleanup
如果該屬性設置為True, 那么控件獲得焦點時,移除出錯的class定義,隱藏錯誤信息,避免和 focusInvalid.一起用。
$(".selector").validate({
focusCleanup: true
})
9: meta
設置meta來封裝驗證規則
$(".selector").validate({
meta: "validate",
})
第四章 自定義錯誤消息的顯示方式
默認情況下,驗證提示信息用label元素來顯示, 並且會添加css class, 通過css可以很方便設置出錯控件以及錯誤信息的顯示方式。
/* 輸入控件驗證出錯*/
form input.error { border:solid 1px red;}
/* 驗證錯誤提示信息*/
form label.error{width: 200px;margin-left: 10px; color: Red;}
如果想自定義顯示方式,可以修改jquery.validate的默認顯示方式
默認用label顯示錯誤消息,可以通過errorElement屬性來修改
errorElement: 錯誤消息的html標簽
$(".selector").validate
errorElement: "em"
})
可以在出錯信息外用其他的元素包裝一層。
wrapper: 錯誤消息的外層封裝html標簽
$(".selector").validate({
wrapper: "li"
})
驗證出錯的css class默認是error,通過errorClass可以修改
errorClass: 驗證出錯時使用的css class
$(".selector").validate({
errorClass: "invalid"
})
還自定義驗證成功時的動作
success: 如果值是字符串,會當做一個css類,如果是一個函數,則執行該函數
$(".selector").validate({
success: "valid"
})
或者
success: function(label) {
label.html(" ").addClass("checked");
}
還可以把錯誤消息統一到一個容器顯示
errorLabelContainer: 將錯誤消息統一到一個容器顯示
$("#myform").validate({
errorLabelContainer: "#messageBox"
})
默認情況下,錯誤消息是放在驗證元素后面的,可以自定義錯誤消息的顯示位置
$(".selector").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
}
})
更進一步可以定義一個組,把幾個地方的出錯信息統一放在一個地方,用error Placement控制把出錯信息放在哪里
groups:定義一個組
$(".selector").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);
}
})
高亮顯示
highlight: 高亮顯示,默認是添加errorClass
unhighlight: 和highlight對應,反高亮顯示
$(".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);
}
});
或者可以完全自定義錯誤顯示
showErrors: 得到錯誤的顯示句柄
$(".selector").validate({
showErrors: function(errorMap, errorList) {
$("#summary").html("Your form contains " + this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
})
第五章 一些常用的驗證腳本
不會寫js了,只能從網上找一些常用的驗證腳本。
// 手機號碼驗證
jQuery.validator.addMethod("mobile", function(value, element) {
var length = value.length;
var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/
return this.optional(element) || (length == 11 && mobile.test(value));
}, "手機號碼格式錯誤");
// 電話號碼驗證
jQuery.validator.addMethod("phone", function(value, element) {
var tel = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
return this.optional(element) || (tel.test(value));
}, "電話號碼格式錯誤");
// 郵政編碼驗證
jQuery.validator.addMethod("zipCode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "郵政編碼格式錯誤");
// QQ號碼驗證
jQuery.validator.addMethod("qq", function(value, element) {
var tel = /^[1-9]\d{4,9}$/;
return this.optional(element) || (tel.test(value));
}, "qq號碼格式錯誤");
// IP地址驗證
jQuery.validator.addMethod("ip", function(value, element) {
var ip = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return this.optional(element) || (ip.test(value) && (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256));
}, "Ip地址格式錯誤");
// 字母和數字的驗證
jQuery.validator.addMethod("chrnum", function(value, element) {
var chrnum = /^([a-zA-Z0-9]+)$/;
return this.optional(element) || (chrnum.test(value));
}, "只能輸入數字和字母(字符A-Z, a-z, 0-9)");
// 中文的驗證
jQuery.validator.addMethod("chinese", function(value, element) {
var chinese = /^[\u4e00-\u9fa5]+$/;
return this.optional(element) || (chinese.test(value));
}, "只能輸入中文");
// 下拉框驗證
$.validator.addMethod("selectNone", function(value, element) {
return value == "請選擇";
}, "必須選擇一項");
// 字節長度驗證
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}個字節之間(一個中文字算2個字節)"));
目錄
List of built-in Validation methods9
轉自http://www.cnblogs.com/buzzlight/archive/2010/06/30/1768364.html
jquery.validate使用攻略
第一章 jquery.validate使用攻略
好幾年不寫JS了,資料整理起來比較慢,格式也有點亂
主要分幾部分
jquery.validate 基本用法
jquery.validate API說明
jquery.validate 自定義
jquery.validate 常見類型的驗證代碼
下載地址
jquery.validate插件的文檔地址
http://docs.jquery.com/Plugins/Validation
jquery.validate插件的主頁
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
jquery.validate插件主頁上提供的demo
http://jquery.bassistance.de/validate/demo/
驗證規則
下面是默認校驗規則,也可以自定義規則
(1)required:true 必輸字段
(2)remote:"check.php" 使用ajax方法調用check.php驗證輸入值
(3)email:true 必須輸入正確格式的電子郵件
(4)url:true 必須輸入正確格式的網址
(5)date:true 必須輸入正確格式的日期
(6)dateISO:true 必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22 只驗證格式,不驗證有效性
(7)number:true 必須輸入合法的數字(負數,小數)
(8)digits:true 必須輸入整數
(9)creditcard: 必須輸入合法的信用卡號
(10)equalTo:"#field" 輸入值必須和#field相同
(11)accept: 輸入擁有合法后綴名的字符串(上傳文件的后綴)
(12)maxlength:5 輸入長度最多是5的字符串(漢字算一個字符)
(13)minlength:10 輸入長度最小是10的字符串(漢字算一個字符)
(14)rangelength:[5,10] 輸入長度必須介於 5 和 10 之間的字符串")(漢字算一個字符)
(15)range:[5,10] 輸入值必須介於 5 和 10 之間
(16)max:5 輸入值不能大於5
(17)min:10 輸入值不能小於10
驗證提示
下面是默認的驗證提示,官網有簡體中文版的驗證提示下載,或者通過jQuery.extend(jQuery.validator.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.",
accept: "Please enter a value with a valid extension.",
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}.")
使用方式
1:
在控件中使用默認驗證規則,例子:
電子郵件(必填)
<input id="email" class="required email" value="email@" />
2:
可以在控件中自定義驗證規則,例子:
自定義(必填,[3,5])
<input id="complex" value="hi" class="{required:true,minlength:3, maxlength:5,
messages:{required:'為什么不輸入一點文字呢',minlength:'輸入的太少了',maxlength:'輸入那么多干嘛'}}" />
3:
通過javascript自定義驗證規則,下面的JS自定義了兩個規則,password和confirm_password
$().ready(function() {
$("#form2").validate({
rules: {
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
}
},
messages: {
password: {
required: "沒有填寫密碼",
minlength: jQuery.format("密碼不能小於{0}個字符")
},
confirm_password: {
required: "沒有確認密碼",
minlength: "確認密碼不能小於{0}個字符",
equalTo: "兩次輸入密碼不一致嘛"
}
}
});
});
required除了設置為true/false之外,還可以使用表達式或者函數,比如
$("#form2").validate({
rules: {
funcvalidate: {
required: function() {return $("#password").val()!=""; }
}
},
messages: {
funcvalidate: {
required: "有密碼的情況下必填"
}
}
});
Html
密碼<input id="password" name="password" type="password" />
確認密碼<input id="confirm_password" name="confirm_password" type="password" />
條件驗證<input id="funcvalidate" name="funcvalidate" value="" />
4:
使用meta自定義驗證信息
首先用JS設置meta
$("#form3").validate({ meta: "validate" });
Html
email<input class="{validate:{required:true, email:true,
messages:{required:'輸入email地址', email:'你輸入的不是有效的郵件地址'}}}"/>
5:
使用meta可以將驗證規則寫在自定義的標簽內,比如validate
JS設置meta
$().ready(function() {
$.metadata.setType("attr", "validate");
$("#form1").validate();
});
Html
<input id="email" name="email"
validate="{required:true, email:true, messages:{required:'輸入email地址', email:'你輸入的不是有效的郵件地址'}}" />
6:
自定義驗證規則
對於復雜的驗證,可以通過jQuery.validator.addMethod添加自定義的驗證規則
官網提供的additional-methods.js里包含一些常用的驗證方式,比如lettersonly,ziprange,nowhitespace等
例子
// 字符驗證
jQuery.validator.addMethod("userName", function(value, element) {
return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
}, "用戶名只能包括中文字、英文字母、數字和下划線");
//然后就可以使用這個規則了
$("#form1").validate({
// 驗證規則
rules: {
userName: {
required: true,
userName: true,
rangelength: [5,10]
}
},
/* 設置錯誤信息 */
messages: {
userName: {
required: "請填寫用戶名",
rangelength: "用戶名必須在5-10個字符之間"
}
},
});
7:
radio、checkbox、select的驗證方式類似
radio的驗證
性別
<span>
男<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}"/><br />
女<input type="radio" id="gender_female" value="f" name="gender" />
</span>
checkbox的驗證
最少選擇兩項
<span>
選項1<input type="checkbox" id="check_1" value="1" name="checkGroup"
class="{required:true,minlength:2, messages:{required:'必須選擇',minlength:'至少選擇2項'}}" /><br />
選項2<input type="checkbox" id="check_2" value="2" name="checkGroup" /><br />
選項3<input type="checkbox" id="check_3" value="3" name="checkGroup" /><br />
</span>
select的驗證
下拉框
<span>
<select id="selectbox" name="selectbox" class="{required:true}">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</span>
8:
Ajax驗證
用remote可以進行Ajax驗證
remote: {
url: "url", //url地址
type: "post", //發送方式
dataType: "json", //數據格式 data: { //要傳遞的數據
username: function() {
return $("#username").val();
}}
}
補充: jQuery Validation插件remote驗證方式的Bug
http://www.cnblogs.com/JeffreyZhao/archive/2009/12/04/jquery-validate-remote-bug.html
第二章 jQuery.validate.js API
| Name |
Type |
| Returns: Validator |
|
| 驗證所選的FORM |
|
| Returns: Boolean |
|
| 檢查是否驗證通過 |
|
| Returns: Options |
|
| 返回元素的驗證規則 |
|
| Returns: Options |
|
| 增加驗證規則。 |
|
| Returns: Options |
|
| 刪除驗證規則 |
|
| Returns: Options |
|
| 刪除特殊屬性並且返回他們 |
|
Custom selectors
| Name |
Type |
Custom selectors:
| Name |
Type |
| 沒有值的篩選器 |
|
| 有值的篩選器 |
|
| 沒選擇的元素的篩選器 |
|
Utilities
| Name |
Type |
String utilities:
| Name |
Type |
| Returns: String |
|
| 用參數代替模板中的 {n}。 |
|
Validator
validate方法返回一個Validator對象, 它有很多方法, 讓你能使用引發校驗程序或者改變form的內容. validator對象有很多方法, 但下面只是列出常用的.
| Name |
Type |
Validator methods:
| Name |
Type |
| Returns: Boolean |
|
| 驗證form返回成功還是失敗 |
|
| Returns: Boolean |
|
| 驗證單個元素是成功還是失敗 |
|
| Returns: undefined |
|
| 把前面驗證的FORM恢復到驗證前原來的狀態 |
|
| Returns: undefined |
|
| 顯示特定的錯誤信息 |
|
There are a few static methods on the validator object:
| Name |
Type |
Validator functions:
| Name |
Type |
| Returns: undefined |
|
| 改變默認的設置 |
|
| Returns: undefined |
|
| 添加一個新的驗證方法. 必須包括一個獨一無二的名字,一個JAVASCRIPT的方法和一個默認的信息 |
|
| Returns: undefined |
|
| 增加組合驗證類型 在一個類里面用多種驗證方法里比較有用 |
|
| Returns: undefined |
|
| 增加組合驗證類型 在一個類里面用多種驗證方法里比較有用,這個是一下子加多個 |
|
[edit ]
List of built-in Validation methods
A set of standard validation methods is provided:
| Name |
Type |
Methods:
| Name |
Type |
| Returns: Boolean |
|
| 必填驗證元素 |
|
| Returns: Boolean |
|
| 必填元素依賴於表達式的結果. |
|
| Returns: Boolean |
|
| 必填元素依賴於回調函數的結果. |
|
| Returns: Boolean |
|
| 請求遠程校驗。url通常是一個遠程調用方法 |
|
| Returns: Boolean |
|
| 設置最小長度 |
|
| Returns: Boolean |
|
| 設置最大長度 |
|
| Returns: Boolean |
|
| 設置一個長度范圍[min,max] |
|
| Returns: Boolean |
|
| 設置最小值. |
|
| Returns: Boolean |
|
| 設置最大值. |
|
| Returns: Boolean |
|
| 設置值的范圍 |
|
| Returns: Boolean |
|
| 驗證電子郵箱格式 |
|
| Returns: Boolean |
|
| 驗證連接格式 |
|
| Returns: Boolean |
|
| 驗證日期格式(類似30/30/2008的格式,不驗證日期准確性只驗證格式) |
|
| Returns: Boolean |
|
| 研制ISO類型的日期格式 |
|
| Returns: Boolean |
|
| 驗證德式的日期格式(29.04.1994 or 1.1.2006) |
|
| Returns: Boolean |
|
| 驗證十進制數字(包括小數的) |
|
| Returns: Boolean |
|
| Makes the element require a decimal number with german format. |
|
| Returns: Boolean |
|
| 驗證整數 |
|
| Returns: Boolean |
|
| 驗證信用卡號 |
|
| Returns: Boolean |
|
| 驗證相同后綴名的字符串 |
|
| Returns: Boolean |
|
| 驗證兩個輸入框的內容是否相同 |
|
| Name |
Type |
| Returns: Boolean |
|
| 驗證美式的電話號碼 |
|
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:定義一個組,把幾個地方的出錯信息同意放在一個地方,用error Placement控制把出錯信息放在哪里
$("#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
})
| nsubmit |
Default: true |
|
| 提交時驗證. 設置唯false就用其他方法去驗證 |
||
| · Code 不用onsubmit驗證,就允許用戶無論用什么方法去驗證,而是提交時, 用 keyup/blur/click 等方法. $(".selector").validate({ onsubmit: false }) |
||
| onfocusout |
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 |
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 |
Default: true |
|
| 在checkboxes 和 radio 點擊時驗證. |
||
| · Code Disables onclick validation of checkboxes and radio buttons. $(".selector").validate({ onclick: false }) |
||
| focusInvalid |
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 |
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 |
|
|
| 為了元數據使用其他插件你要包裝 你的驗證規則 在他們自己的項目中可以用這個特殊的選項 |
||
| 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"> <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 |
Default: "error" |
|
| 創建錯誤類的名字為了去尋找存在的錯誤標簽和增加它到驗證失敗的元素中去。 |
||
| · Code Sets the error class to "invalid". $(".selector").validate({ errorClass: "invalid" }) |
||
| errorElement |
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 |
|
|
| 在出錯信息外用其他的元素包裝一層。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 |
|
|
| 把錯誤信息統一放在一個容器里面。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 |
|
|
| 顯示或者隱藏驗證信息 |
||
| 使用一個額外的容器去顯示錯誤信息 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"> <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 |
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 |
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"> <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 |
|
|
| 成功時的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"> <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"> <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 |
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); } }); |
||
| unhighlight |
Default: 默認是去掉error類 |
|
| Called to revert changes made by option highlight, same arguments as highlight. |
||
第三章 自定義jquery-validate的驗證行為
1: 自定義表單提交
設置submitHandler來自定義表單提交動作
$(".selector").validate({
submitHandler: function(form) { alert("驗證通過"); }
});
如果需要提交表單,可以調用
form.submit(); 或者$(form).ajaxSubmit();
2: 調試模式
將debug設置為true,表單不會提交,只進行檢查,方便調試
$(".selector").validate({
debug: true
})
3: 設置validate的默認值
使用setDefaults可以設置validate的默認值,比如默認所有表單驗證都是在debug模式下進行
$.validator.setDefaults({
debug: true
})
4: 某些元素不驗證
設置ignore屬性可以忽略某些元素不驗證
$(".selector").validate({
ignore: "ignore"
})
5: 驗證時機
jquery.validate可以很方便的設置在什么時候觸發驗證動作
onsubmit: 提交時是否驗證
$(".selector").validate({
onsubmit: false
})
onfocusout: 失去焦點時驗證(checkboxes/radio除外)
$(".selector").validate({
onfocusout: false
})
onkeyup: 在keyup時驗證
$(".selector").validate({
onkeyup: false
})
onclick: 在checkboxes、radio點擊時驗證.
$(".selector").validate({
onclick: false
})
6: 重寫驗證規則和驗證提示信息
//重寫max的的驗證提示信息
$.validator.messages.max = jQuery.format("Your totals musn't exceed {0}!");
//重寫equal方法
$.validator.methods.equal = function(value, element, param) {
return value == param;
};
7: focusInvalid 是否把焦點聚焦在最后一個動作或者最近的一次出錯上
$(".selector").validate({
focusInvalid: false
})
8: focusCleanup
如果該屬性設置為True, 那么控件獲得焦點時,移除出錯的class定義,隱藏錯誤信息,避免和 focusInvalid.一起用。
$(".selector").validate({
focusCleanup: true
})
9: meta
設置meta來封裝驗證規則
$(".selector").validate({
meta: "validate",
})
第四章 自定義錯誤消息的顯示方式
默認情況下,驗證提示信息用label元素來顯示, 並且會添加css class, 通過css可以很方便設置出錯控件以及錯誤信息的顯示方式。
/* 輸入控件驗證出錯*/
form input.error { border:solid 1px red;}
/* 驗證錯誤提示信息*/
form label.error{width: 200px;margin-left: 10px; color: Red;}
如果想自定義顯示方式,可以修改jquery.validate的默認顯示方式
默認用label顯示錯誤消息,可以通過errorElement屬性來修改
errorElement: 錯誤消息的html標簽
$(".selector").validate
errorElement: "em"
})
可以在出錯信息外用其他的元素包裝一層。
wrapper: 錯誤消息的外層封裝html標簽
$(".selector").validate({
wrapper: "li"
})
驗證出錯的css class默認是error,通過errorClass可以修改
errorClass: 驗證出錯時使用的css class
$(".selector").validate({
errorClass: "invalid"
})
還自定義驗證成功時的動作
success: 如果值是字符串,會當做一個css類,如果是一個函數,則執行該函數
$(".selector").validate({
success: "valid"
})
或者
success: function(label) {
label.html(" ").addClass("checked");
}
還可以把錯誤消息統一到一個容器顯示
errorLabelContainer: 將錯誤消息統一到一個容器顯示
$("#myform").validate({
errorLabelContainer: "#messageBox"
})
默認情況下,錯誤消息是放在驗證元素后面的,可以自定義錯誤消息的顯示位置
$(".selector").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
}
})
更進一步可以定義一個組,把幾個地方的出錯信息統一放在一個地方,用error Placement控制把出錯信息放在哪里
groups:定義一個組
$(".selector").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);
}
})
高亮顯示
highlight: 高亮顯示,默認是添加errorClass
unhighlight: 和highlight對應,反高亮顯示
$(".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);
}
});
或者可以完全自定義錯誤顯示
showErrors: 得到錯誤的顯示句柄
$(".selector").validate({
showErrors: function(errorMap, errorList) {
$("#summary").html("Your form contains " + this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
})
第五章 一些常用的驗證腳本
不會寫js了,只能從網上找一些常用的驗證腳本。
// 手機號碼驗證
jQuery.validator.addMethod("mobile", function(value, element) {
var length = value.length;
var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/
return this.optional(element) || (length == 11 && mobile.test(value));
}, "手機號碼格式錯誤");
// 電話號碼驗證
jQuery.validator.addMethod("phone", function(value, element) {
var tel = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
return this.optional(element) || (tel.test(value));
}, "電話號碼格式錯誤");
// 郵政編碼驗證
jQuery.validator.addMethod("zipCode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "郵政編碼格式錯誤");
// QQ號碼驗證
jQuery.validator.addMethod("qq", function(value, element) {
var tel = /^[1-9]\d{4,9}$/;
return this.optional(element) || (tel.test(value));
}, "qq號碼格式錯誤");
// IP地址驗證
jQuery.validator.addMethod("ip", function(value, element) {
var ip = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return this.optional(element) || (ip.test(value) && (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256));
}, "Ip地址格式錯誤");
// 字母和數字的驗證
jQuery.validator.addMethod("chrnum", function(value, element) {
var chrnum = /^([a-zA-Z0-9]+)$/;
return this.optional(element) || (chrnum.test(value));
}, "只能輸入數字和字母(字符A-Z, a-z, 0-9)");
// 中文的驗證
jQuery.validator.addMethod("chinese", function(value, element) {
var chinese = /^[\u4e00-\u9fa5]+$/;
return this.optional(element) || (chinese.test(value));
}, "只能輸入中文");
// 下拉框驗證
$.validator.addMethod("selectNone", function(value, element) {
return value == "請選擇";
}, "必須選擇一項");
// 字節長度驗證
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}個字節之間(一個中文字算2個字節)"));
