jQuery.Validate驗證庫 2

四、使用方式
1.將校驗規則寫到控件中

Js代碼 
  1. <script src="../js/jquery.js" type="text/javascript"></script>  
  2. <script src="../js/jquery.validate.js" type="text/javascript"></script>  
  3. <script src="./js/jquery.metadata.js" type="text/javascript"></script>  
  4. $().ready(function() {  
  5.  $("#signupForm").validate();  
  6. });  
  7.   
  8. <form id="signupForm" method="get" action="">  
  9.     <p>  
  10.         <label for="firstname">Firstname</label>  
  11.         <input id="firstname" name="firstname" class="required" />  
  12.     </p>  
  13.  <p>  
  14.   <label for="email">E-Mail</label>  
  15.   <input id="email" name="email" class="required email" />  
  16.  </p>  
  17.  <p>  
  18.   <label for="password">Password</label>  
  19.   <input id="password" name="password" type="password" class="{required:true,minlength:5}" />  
  20.  </p>  
  21.  <p>  
  22.   <label for="confirm_password">確認密碼</label>  
  23.   <input id="confirm_password" name="confirm_password" type="password" class="{required:true,minlength:5,equalTo:'#password'}" />  
  24.  </p>  
  25.     <p>  
  26.         <input class="submit" type="submit" value="Submit"/>  
  27.     </p>  
  28. </form>  

使用class="{}"的方式,必須引入包:jquery.metadata.js

可以使用如下的方法,修改提示內容:

Js代碼  
  1. class="{required:true,minlength:5,messages:{required:'請輸入內容'}}"  

在使用equalTo關鍵字時,後面的內容必須加上引號,如下代碼:

Js代碼   
  1. class="{required:true,minlength:5,equalTo:'#password'}"  

另外一個方式,使用關鍵字:meta(爲了元數據使用其他插件你要包裝 你的驗證規則 在他們自己的項目中可以用這個特殊的選項)

Tell the validation plugin to look inside a validate-property in metadata for validation rules.
例如:

Js代碼  
  1. meta: "validate"  
  2. <input id="password" name="password" type="password" class="{validate:{required:true,minlength:5}}" />  

 再有一種方式:

Js代碼  
  1. $.metadata.setType("attr""validate");  

這樣可以使用validate="{required:true}"的方式,或者class="required",但class="{required:true,minlength:5}"將不起作用 

2.將校驗規則寫到代碼中


 

Html代碼  
  1. $().ready(function() {  
  2.  $("#signupForm").validate({  
  3.         rules: {  
  4.    firstname: "required",  
  5.    email: {  
  6.     required: true,  
  7.     email: true  
  8.    },  
  9.    password: {  
  10.     required: true,  
  11.     minlength: 5  
  12.    },  
  13.    confirm_password: {  
  14.     required: true,  
  15.     minlength: 5,  
  16.     equalTo: "#password"  
  17.    }  
  18.   },  
  19.         messages: {  
  20.    firstname: "請輸入姓名",  
  21.    email: {  
  22.     required: "請輸入Email地址",  
  23.     email: "請輸入正確的email地址"  
  24.    },  
  25.    password: {  
  26.     required: "請輸入密碼",  
  27.     minlength: jQuery.format("密碼不能小於{0}個字符")  
  28.    },  
  29.    confirm_password: {  
  30.     required: "請輸入確認密碼",  
  31.     minlength: "確認密碼不能小於5個字符",  
  32.     equalTo: "兩次輸入密碼不一致不一致"  
  33.    }  
  34.   }  
  35.     });  
  36. });  
  37. //messages處,如果某個控件沒有message,將調用默認的信息  
  38.   
  39. <form id="signupForm" method="get" action="">  
  40.     <p>  
  41.         <label for="firstname">Firstname</label>  
  42.         <input id="firstname" name="firstname" />  
  43.     </p>  
  44.  <p>  
  45.   <label for="email">E-Mail</label>  
  46.   <input id="email" name="email" />  
  47.  </p>  
  48.  <p>  
  49.   <label for="password">Password</label>  
  50.   <input id="password" name="password" type="password" />  
  51.  </p>  
  52.  <p>  
  53.   <label for="confirm_password">確認密碼</label>  
  54.   <input id="confirm_password" name="confirm_password" type="password" />  
  55.  </p>  
  56.     <p>  
  57.         <input class="submit" type="submit" value="Submit"/>  
  58.     </p>  
  59. </form>  

 

required:true 必須有值
required:"#aa:checked"表達式的值爲真,則需要驗證
required:function(){}返回爲真,表時需要驗證
後邊兩種常用於,表單中需要同時填或不填的元素
 
五、常用方法及注意問題
1.用其他方式替代默認的SUBMIT

Js代碼  
  1. $().ready(function() {  
  2.  $("#signupForm").validate({  
  3.         submitHandler:function(form){  
  4.             alert("submitted");     
  5.             form.submit();  
  6.         }      
  7.     });  
  8. });  

 


可以設置validate的默認值,寫法如下:

Js代碼  
  1. $.validator.setDefaults({  
  2.  submitHandler: function(form) { alert("submitted!");form.submit(); }  
  3. });  

 


如果想提交表單, 需要使用form.submit()而不要使用$(form).submit()

2.debug,如果這個參數爲true,那麼表單不會提交,只進行檢查,調試時十分方便

Js代碼  
  1. $().ready(function() {  
  2.  $("#signupForm").validate({  
  3.         debug:true  
  4.     });  
  5. });  

 


如果一個頁面中有多個表單,用

Js代碼  
  1. $.validator.setDefaults({  
  2.    debug: true  
  3. })  

 

3.ignore:忽略某些元素不驗證

Js代碼  
  1. ignore: ".ignore"  

 

4.errorPlacement:Callback  Default: 把錯誤信息放在驗證的元素後面  
指明錯誤放置的位置,默認情況是:error.appendTo(element.parent());即把錯誤信息放在驗證的元素後面 
errorPlacement: function(error, element) {   
    error.appendTo(element.parent());   
}
//示例:

Html代碼  
  1. <tr>  
  2.     <td class="label"><label id="lfirstname" for="firstname">First Name</label></td>  
  3.     <td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>  
  4.     <td class="status"></td>  
  5. </tr>  
  6. <tr>  
  7.     <td style="padding-right: 5px;">  
  8.         <input id="dateformat_eu" name="dateformat" type="radio" value="0" />  
  9.         <label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>  
  10.     </td>  
  11.     <td style="padding-left: 5px;">  
  12.         <input id="dateformat_am" name="dateformat" type="radio" value="1"  />  
  13.         <label id="ldateformat_am" for="dateformat_am">02/14/07</label>  
  14.     </td>  
  15.     <td></td>  
  16. </tr>  
  17. <tr>  
  18.     <td class="label">&nbsp;</td>  
  19.     <td class="field" colspan="2">  
  20.         <div id="termswrap">  
  21.             <input id="terms" type="checkbox" name="terms" />  
  22.             <label id="lterms" for="terms">I have read and accept the Terms of Use.</label>  
  23.         </div>  
  24.     </td>  
  25. </tr>  
Js代碼  
  1. errorPlacement: function(error, element) {  
  2.     if ( element.is(":radio") )  
  3.         error.appendTo( element.parent().next().next() );  
  4.     else if ( element.is(":checkbox") )  
  5.         error.appendTo ( element.next() );  
  6.     else  
  7.         error.appendTo( element.parent().next() );  
  8. }  
 
代碼的作用是:一般情況下把錯誤信息顯示在<td class="status"></td>中,如果是radio顯示在<td></td>中,如果是checkbox顯示在內容的後面

errorClass:String  Default: "error"  
指定錯誤提示的css類名,可以自定義錯誤提示的樣式
errorElement:String  Default: "label"  
用什麼標籤標記錯誤,默認的是label你可以改成em
errorContainer:Selector  
顯示或者隱藏驗證信息,可以自動實現有錯誤信息出現時把容器屬性變爲顯示,無錯誤時隱藏,用處不大
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer:Selector 
把錯誤信息統一放在一個容器裏面。
wrapper:String
用什麼標籤再把上邊的errorELement包起來
一般這三個屬性同時使用,實現在一個容器內顯示所有錯誤提示的功能,並且沒有信息時自動隱藏

Js代碼  
  1. errorContainer: "div.error",  
  2. errorLabelContainer: $("#signupForm div.error"),  
  3. wrapper: "li"  

 


 
設置錯誤提示的樣式,可以增加圖標顯示

Js代碼  
  1. input.error { border: 1px solid red; }  
  2. label.error {  
  3.   background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;  
  4.   padding-left: 16px;  
  5.   padding-bottom: 2px;  
  6.   font-weight: bold;  
  7.   color: #EA5200;  
  8. }  
  9. label.checked {  
  10.   background:url("./demo/images/checked.gif") no-repeat 0px 0px;  
  11. }  
  12. success:String,Callback   

 


要驗證的元素通過驗證後的動作,如果跟一個字符串,會當做一個css類,也可跟一個函數

Js代碼 
  1. success: function(label) {  
  2.     // set &nbsp; as text for IE  
  3.     label.html("&nbsp;").addClass("checked");  
  4.     //label.addClass("valid").text("Ok!")  
  5. }  

 


添加"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 一起用
 
// 重置表單

Java代碼  
  1. $().ready(function() {  
  2.  var validator = $("#signupForm").validate({  
  3.         submitHandler:function(form){  
  4.             alert("submitted");     
  5.             form.submit();  
  6.         }      
  7.     });  
  8.     $("#reset").click(function() {  
  9.         validator.resetForm();  
  10.     });  
  11. });  

 remote:URL

使用ajax方式進行驗證,默認會提交當前驗證的值到遠程地址,如果需要提交其他的值,可以使用data選項

Js代碼  
  1. remote: "check-email.php"  
  2. remote: {  
  3.     url: "check-email.php",     //後臺處理程序  
  4.     type: "post",               //數據發送方式  
  5.     dataType: "json",           //接受數據格式     
  6.     data: {                     //要傳遞的數據  
  7.         username: function() {  
  8.             return $("#username").val();  
  9.         }  
  10.     }  
  11. }  

 

遠程地址只能輸出 "true" 或 "false",不能有其它輸出
 
 
addMethod:name, method, message
自定義驗證方法


 

Js代碼 
  1. // 中文字兩個字節  
  2. jQuery.validator.addMethod("byteRangeLength"function(value, element, param) {  
  3.     var length = value.length;  
  4.     for(var i = 0; i < value.length; i++){  
  5.         if(value.charCodeAt(i) > 127){  
  6.             length++;  
  7.         }  
  8.     }  
  9.   return this.optional(element) || ( length >= param[0] && length <= param[1] );     
  10. }, $.validator.format("請確保輸入的值在{0}-{1}個字節之間(一箇中文字算2個字節)"));  
  11.   
  12. // 郵政編碼驗證     
  13. jQuery.validator.addMethod("isZipCode"function(value, element) {     
  14.     var tel = /^[0-9]{6}$/;  
  15.     return this.optional(element) || (tel.test(value));  
  16. }, "請正確填寫您的郵政編碼");  

 

radio和checkbox、select的驗證
radio的required表示必須選中一個

Html代碼  
  1. <input  type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />  
  2. <input  type="radio" id="gender_female" value="f" name="gender"/>  
  3. checkbox的required表示必須選中  
  4. <input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />  
  5. checkbox的minlength表示必須選中的最小個數,maxlength表示最大的選中個數,rangelength:[2,3]表示選中個數區間  
  6. <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />  
  7. <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />  
  8. <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />  
  9.   
  10. select的required表示選中的value不能爲空  
  11. <select id="jungle" name="jungle" title="Please select something!" class="{required:true}">  
  12.     <option value=""></option>  
  13.     <option value="1">Buga</option>  
  14.     <option value="2">Baga</option>  
  15.     <option value="3">Oi</option>  
  16. </select>  
  17. select的minlength表示選中的最小個數(可多選的select),maxlength表示最大的選中個數,rangelength:[2,3]表示選中個數區間  
  18. <select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">  
  19.     <option value="b">Banana</option>  
  20.     <option value="a">Apple</option>  
  21.     <option value="p">Peach</option>  
  22.     <option value="t">Turtle</option>  
  23. </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頁面,而提交按鈕就一個,這時就需要將驗證提示信息統一放在一個位置,好方便查看,如圖:

pic21

要實現這個效果只需在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”的驗證規則,在驗證規則裏我首先定義了個手機驗證的正則表達式,然後將值放入正則表達式進行驗證,返回驗證結果,返回的錯誤消息是“請輸入正確的手機號碼”。

這樣就完成了一個簡單的手機號碼驗證規則擴展。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章