四、使用方式
1.將校驗規則寫到控件中
- <script src="../js/jquery.js" type="text/javascript"></script>
- <script src="../js/jquery.validate.js" type="text/javascript"></script>
- <script src="./js/jquery.metadata.js" type="text/javascript"></script>
- $().ready(function() {
- $("#signupForm").validate();
- });
- <form id="signupForm" method="get" action="">
- <p>
- <label for="firstname">Firstname</label>
- <input id="firstname" name="firstname" class="required" />
- </p>
- <p>
- <label for="email">E-Mail</label>
- <input id="email" name="email" class="required email" />
- </p>
- <p>
- <label for="password">Password</label>
- <input id="password" name="password" type="password" class="{required:true,minlength:5}" />
- </p>
- <p>
- <label for="confirm_password">確認密碼</label>
- <input id="confirm_password" name="confirm_password" type="password" class="{required:true,minlength:5,equalTo:'#password'}" />
- </p>
- <p>
- <input class="submit" type="submit" value="Submit"/>
- </p>
- </form>
使用class="{}"的方式,必須引入包:jquery.metadata.js
可以使用如下的方法,修改提示內容:
- class="{required:true,minlength:5,messages:{required:'請輸入內容'}}"
在使用equalTo關鍵字時,後面的內容必須加上引號,如下代碼:
- class="{required:true,minlength:5,equalTo:'#password'}"
另外一個方式,使用關鍵字:meta(爲了元數據使用其他插件你要包裝 你的驗證規則 在他們自己的項目中可以用這個特殊的選項)
Tell the validation plugin to look inside a validate-property in metadata for validation rules.
例如:
- meta: "validate"
- <input id="password" name="password" type="password" class="{validate:{required:true,minlength:5}}" />
再有一種方式:
- $.metadata.setType("attr", "validate");
這樣可以使用validate="{required:true}"的方式,或者class="required",但class="{required:true,minlength:5}"將不起作用
2.將校驗規則寫到代碼中
- $().ready(function() {
- $("#signupForm").validate({
- rules: {
- firstname: "required",
- email: {
- required: true,
- email: true
- },
- password: {
- required: true,
- minlength: 5
- },
- confirm_password: {
- required: true,
- minlength: 5,
- equalTo: "#password"
- }
- },
- messages: {
- firstname: "請輸入姓名",
- email: {
- required: "請輸入Email地址",
- email: "請輸入正確的email地址"
- },
- password: {
- required: "請輸入密碼",
- minlength: jQuery.format("密碼不能小於{0}個字符")
- },
- confirm_password: {
- required: "請輸入確認密碼",
- minlength: "確認密碼不能小於5個字符",
- equalTo: "兩次輸入密碼不一致不一致"
- }
- }
- });
- });
- //messages處,如果某個控件沒有message,將調用默認的信息
- <form id="signupForm" method="get" action="">
- <p>
- <label for="firstname">Firstname</label>
- <input id="firstname" name="firstname" />
- </p>
- <p>
- <label for="email">E-Mail</label>
- <input id="email" name="email" />
- </p>
- <p>
- <label for="password">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>
- <input class="submit" type="submit" value="Submit"/>
- </p>
- </form>
required:true 必須有值
required:"#aa:checked"表達式的值爲真,則需要驗證
required:function(){}返回爲真,表時需要驗證
後邊兩種常用於,表單中需要同時填或不填的元素
五、常用方法及注意問題
1.用其他方式替代默認的SUBMIT
- $().ready(function() {
- $("#signupForm").validate({
- submitHandler:function(form){
- alert("submitted");
- form.submit();
- }
- });
- });
可以設置validate的默認值,寫法如下:
- $.validator.setDefaults({
- submitHandler: function(form) { alert("submitted!");form.submit(); }
- });
如果想提交表單, 需要使用form.submit()而不要使用$(form).submit()
2.debug,如果這個參數爲true,那麼表單不會提交,只進行檢查,調試時十分方便
- $().ready(function() {
- $("#signupForm").validate({
- debug:true
- });
- });
如果一個頁面中有多個表單,用
- $.validator.setDefaults({
- debug: true
- })
3.ignore:忽略某些元素不驗證
- ignore: ".ignore"
4.errorPlacement:Callback Default: 把錯誤信息放在驗證的元素後面
指明錯誤放置的位置,默認情況是:error.appendTo(element.parent());即把錯誤信息放在驗證的元素後面
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
//示例:
- <tr>
- <td class="label"><label id="lfirstname" for="firstname">First Name</label></td>
- <td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>
- <td class="status"></td>
- </tr>
- <tr>
- <td style="padding-right: 5px;">
- <input id="dateformat_eu" name="dateformat" type="radio" value="0" />
- <label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>
- </td>
- <td style="padding-left: 5px;">
- <input id="dateformat_am" name="dateformat" type="radio" value="1" />
- <label id="ldateformat_am" for="dateformat_am">02/14/07</label>
- </td>
- <td></td>
- </tr>
- <tr>
- <td class="label"> </td>
- <td class="field" colspan="2">
- <div id="termswrap">
- <input id="terms" type="checkbox" name="terms" />
- <label id="lterms" for="terms">I have read and accept the Terms of Use.</label>
- </div>
- </td>
- </tr>
- errorPlacement: function(error, element) {
- if ( element.is(":radio") )
- error.appendTo( element.parent().next().next() );
- else if ( element.is(":checkbox") )
- error.appendTo ( element.next() );
- else
- error.appendTo( element.parent().next() );
- }
errorClass:String Default: "error"
指定錯誤提示的css類名,可以自定義錯誤提示的樣式
errorElement:String Default: "label"
用什麼標籤標記錯誤,默認的是label你可以改成em
errorContainer:Selector
顯示或者隱藏驗證信息,可以自動實現有錯誤信息出現時把容器屬性變爲顯示,無錯誤時隱藏,用處不大
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer:Selector
把錯誤信息統一放在一個容器裏面。
wrapper:String
用什麼標籤再把上邊的errorELement包起來
一般這三個屬性同時使用,實現在一個容器內顯示所有錯誤提示的功能,並且沒有信息時自動隱藏
- errorContainer: "div.error",
- errorLabelContainer: $("#signupForm div.error"),
- wrapper: "li"
設置錯誤提示的樣式,可以增加圖標顯示
- 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;
- }
- success:String,Callback
要驗證的元素通過驗證後的動作,如果跟一個字符串,會當做一個css類,也可跟一個函數
- success: function(label) {
- // set as text for IE
- label.html(" ").addClass("checked");
- //label.addClass("valid").text("Ok!")
- }
添加"valid" 到驗證元素, 在CSS中定義的樣式<style>label.valid {}</style>
success: "valid"
nsubmit: Boolean Default: true
提交時驗證. 設置唯false就用其他方法去驗證
onfocusout:Boolean Default: true
失去焦點是驗證(不包括checkboxes/radio buttons)
onkeyup:Boolean Default: true
在keyup時驗證.
Default: true
在checkboxes 和 radio 點擊時驗證
focusInvalid:Boolean Default: true
提交表單後,未通過驗證的表單(第一個或提交之前獲得焦點的未通過驗證的表單)會獲得焦點
focusCleanup:Boolean Default: false
如果是true那麼當未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用
// 重置表單
- $().ready(function() {
- var validator = $("#signupForm").validate({
- submitHandler:function(form){
- alert("submitted");
- form.submit();
- }
- });
- $("#reset").click(function() {
- validator.resetForm();
- });
- });
remote:URL
使用ajax方式進行驗證,默認會提交當前驗證的值到遠程地址,如果需要提交其他的值,可以使用data選項
- remote: "check-email.php"
- remote: {
- url: "check-email.php", //後臺處理程序
- type: "post", //數據發送方式
- dataType: "json", //接受數據格式
- data: { //要傳遞的數據
- username: function() {
- return $("#username").val();
- }
- }
- }
遠程地址只能輸出 "true" 或 "false",不能有其它輸出
addMethod:name, method, message
自定義驗證方法
- // 中文字兩個字節
- 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個字節)"));
- // 郵政編碼驗證
- jQuery.validator.addMethod("isZipCode", function(value, element) {
- var tel = /^[0-9]{6}$/;
- return this.optional(element) || (tel.test(value));
- }, "請正確填寫您的郵政編碼");
radio和checkbox、select的驗證
radio的required表示必須選中一個
- <input type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />
- <input type="radio" id="gender_female" value="f" name="gender"/>
- checkbox的required表示必須選中
- <input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />
- checkbox的minlength表示必須選中的最小個數,maxlength表示最大的選中個數,rangelength:[2,3]表示選中個數區間
- <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, 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表示選中的value不能爲空
- <select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
- <option value=""></option>
- <option value="1">Buga</option>
- <option value="2">Baga</option>
- <option value="3">Oi</option>
- </select>
- select的minlength表示選中的最小個數(可多選的select),maxlength表示最大的選中個數,rangelength:[2,3]表示選中個數區間
- <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是監控form,在任何提交表單的操作前jQuery.Validate都會檢測表單裏的輸入項是否滿足規則,滿足才允許提交。所以需
要在jQuery(document).ready()時爲form進行驗證註冊
具體代碼如下:
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#form1").validate();
});
</script>
</body>
jQuery.Validate爲我們提供了3種驗證編寫方式,各有優缺點:
1、在input對象中書寫class樣式指定驗證規則或屬性驗證規則:
如<input type=”text” class=”required”/>
最簡單、最便捷,提示消息使用jQuery.Validate的內置的消息(自定義擴展驗證規則也屬於此項),但是由於是以樣式名的方式進行驗證,導致了日後修改必須找到相應的input對象,同時無法使用高級驗證規則,具體說明請向下看
2、同第1條,這種驗證規則方式也是在input對象中書寫class樣式,只不過書寫的方式改爲了JSON格式,但是這種方式提供了自定義驗證消息的支持:
如<input type=”text” class="{required:true,minlength:5,,messages:{required:'請輸入內容'}”/>
簡單、方便,但個人認爲有點臃腫,還是和第1條一樣和相對應的input對象糾纏在一起,並且還增加消息自定義,使得input對象變的更大了,干擾了頁面代碼的閱讀,但可以使用高級驗證規則(實際就是將第3種JS以JSON的格式放到具體的class中
3、這種方式使用純JS的方式:
如:
$().ready(function() {
$("#aspnetform").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}})
})
很好的解決了HTML和驗證規則的分離,就是書寫較爲麻煩,需要單獨寫JS腳本,但好處是可以統一驗證規範,將每個頁面的驗證規則都寫在頭部的腳本中,方便日後維護。
注意:以上3種驗證方式的消息如果未指定都會默認調用內置的消息
1、在使用上一篇中第2種方式,以JSON的格式編寫驗證規則,影響了正常的class使用,如何處理?
2、在ASP.NET下,所有的按鈕都會提交form表單,所以都會引發驗證,如何處理?
3、我希望驗證的提示信息可以在統一的地方顯示,如何處理?
4、我在開發的過程中,我不確定所編寫的規則是否正確,如何進行調試?
5、我使用的是微軟AJAX控件,想監控dropdownlist是否選擇,爲何不起作用?
6、radiobox,checkbox,listbox如何進行高級應用?如何指定選擇數量?
1點:在使用上一篇中第2種方式,以JSON的格式編寫驗證規則,影響了正常的class使用,如何處理?(具體見Middle-4.aspx)
首先看下使用第2種方式是如何編寫驗證規則的:
<asp:TextBox ID="txtPwd" TextMode="Password" runat="server" CssClass="{required:true,minlength:6,messages:{required:'你不輸入密碼怎麼行呢?',minlength:'密碼太短啦至少6位'}}"></asp:TextBox>
可以看到這樣寫驗證規則雖然簡單,但是如果我要爲這個控件應用其他樣式怎麼辦?所以現在就是處理這個問題的時候了,在頁面的頭部加上一句代碼:
jQuery.metadata.setType("attr", "validate");
由於這種驗證規則方式需要依賴jQuery.metadata纔可以正常運作,所以我們需要在jQuery.metadata上做文章,分析下jQuery.metadata的代碼,可以看到,默認情況下它是檢測控件的class屬性:
defaults : {
type: 'class',
name: 'metadata',
cre: /({.*})/,
single: 'metadata'
}
那我們可不可以更改這個屬性呢?肯定是可以的,就是在頁面上加上那句代碼,更改其檢測的屬性。
接着我們還需要修改下頁面中的代碼,將原來所有的"CssClass”改爲我們更改的檢測屬性"validate”、
這樣就很好的更改了驗證規則所存放的屬性了。
第2點:在ASP.NET下,所有的按鈕都會提交form表單,所以都會引發驗證,如何處理?(具體見Middle-4.aspx中btnNoValidate按鈕)
在實際的開發當中,一個頁面上總會有N個按鈕,由於ASP.NET的機制特性,所有的控件都會回發頁面,也就提交了表單,但是此時整個表單都被jQuery.Validate所監控,所以只要頁面中有某個地方不符合驗證規則,任何回發頁面的操作都會被攔截住,但是實際上我們需要引發驗證的按鈕只有1或者2個,而其他按鈕不需要,這時我們就要想辦法了。
其實很簡單,就是爲不需要引發驗證的控件加個樣式"cancel"即可,代碼如下:
<asp:Button ID="btnNoValidate" runat="server" Text="點我不會引發驗證哦" CssClass="cancel" />
怎麼樣很簡單吧?
第3點:我希望驗證的提示信息可以在統一的地方顯示,如何處理?(具體見Middle-5.aspx)
在開發的過程當中,會有一些特殊的需求,就比如頁面上使用了tab頁面,而提交按鈕就一個,這時就需要將驗證提示信息統一放在一個位置,好方便查看,如圖:
要實現這個效果只需在JS編寫驗證規則時添加:
errorPlacement: function(error, element) {
error.html(error.html()+"<br/>");
error.appendTo("#errorContainer");
}
error是一個label對象裏面包含了錯誤消息,element則是驗證未通過的對象元素,通過errorPlacement可以方便的將驗證提示信息統一放入一個位置。
第4點:我在開發的過程中,我不確定所編寫的規則是否正確,如何進行調試?(具體見Middle-5.aspx)
這個就比較簡單了,jQuery.Validate默認已經爲我們考慮過了,只需在JS編寫規則時添加一個屬性:
debug:true
這樣就表示現在在調試,這時不會提交表單。
第5點:我使用的是微軟AJAX控件,想監控dropdownlist是否選擇,爲何不起作用?(具體見Middle-5.aspx中的性別)
在使用微軟AJAX控件中的dropdownlist級聯時,比如省市區聯動,如果省沒有選擇,則市和區都是灰的,是disabled狀態,是被禁用的,類似代碼如下:
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="required" disabled="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="1">男</asp:ListItem>
<asp:ListItem Value="0">女</asp:ListItem>
</asp:DropDownList>
我這邊是強制把這個DropDownList禁用了,這時如果爲這個控件加上“required”將不會有任何反應,因爲在jQuery.Validate代碼中默認是不驗證的,具體代碼見jQuery.Validate.js414行:
not(":submit, :reset, :image, [disabled]")
所以爲了方便我們使用,我們修改下代碼,將[disabled]"去除,改爲:
not(":submit, :reset, :image")
這樣再刷新下頁面,驗證就起作用了。
第6點:radiobox,checkbox,listbox如何進行高級應用?如何指定選擇數量?(具體請見radio-checkbox-select-demo.html)
這點我直接引用了官方關於radiobox,checkbox,listbox應用的例子,因爲官方的例子已經寫的非常好了。
1、擴展驗證規則,jQuery.Validate只提供了一些基本的驗證功能,並不能滿足我們日常開發的需求,所以我們要爲jQuery.Validate擴展驗證規則。
2、分組驗證,在開發的時候有時會遇到的一個問題就是,不同按鈕引發不同的驗證。
首先來介紹下第一點:擴展驗證規則,在jQuery.Validate默認的驗證規則無法滿足我們的日常開發需求的時候,我們需要根據自己的業務需求指定一些相應的規則。(具體見MasterPage.master)
爲了擴展驗證規則,我們首先要看下jQuery.Validate爲我們提供的擴展方法:
addMethod: function(name, method, message) {
$.validator.methods[name] = method;
$.validator.messages[name] = message;
if (method.length < 3) {
$.validator.addCla***ules(name, $.validator.normalizeRule(name));
}
},
這段代碼就是用來擴展驗證規則的,意思很簡單,就是向jQuery.Validate添加驗證方法。
接收3個參數:name-驗證規則名
method-驗證規則實現函數(function)
message-驗證不通過顯示的錯誤消息
當我們調用了這個方法後,我們所寫的規則自動就會加入到jQuery.Validate規則中。
好了,我們看下具體如何實現:
手機號碼驗證:
jQuery.validator.addMethod("telphoneValid", function(value, element) {
var tel = /^(130|131|132|133|134|135|136|137|138|139|150|153|157|158|159|180|187|188|189)\d{8}$/;
return tel.test(value) || this.optional(element);
}, "請輸入正確的手機號碼");
這邊的method需要注意的是,這個method實現函數接收2個元素:
value:檢測的對象的值
element:檢測的對象
這邊我定義了一個名爲“telphoneValid”的驗證規則,在驗證規則裏我首先定義了個手機驗證的正則表達式,然後將值放入正則表達式進行驗證,返回驗證結果,返回的錯誤消息是“請輸入正確的手機號碼”。
這樣就完成了一個簡單的手機號碼驗證規則擴展。