之前一篇文章介紹了jQuery Validate表單驗證入門的基礎知識,詳細內容參見《jQuery Validate表單驗證入門學習》,今天這篇文章深入學習jQuery Validate表單驗證,以下就是文章的全部內容:
1、用其他方式替代默認的 SUBMIT
$().ready(function() { $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); });
使用 ajax 方式
$(".selector").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } })
可以設置 validate 的默認值,寫法如下:
$.validator.setDefaults({ submitHandler: function(form) { alert("submitted!");form.submit(); } });
如果想提交表單, 需要使用 form.submit(),而不要使用 $(form).submit()。
2、debug,只驗證不提交表單
如果這個參數為true,那么表單不會提交,只進行檢查,調試時十分方便。
$().ready(function() { $("#signupForm").validate({ debug:true }); });
如果一個頁面中有多個表單都想設置成為 debug,則使用:
$.validator.setDefaults({ debug: true })
3、ignore:忽略某些元素不驗證
ignore: ".ignore"
4、更改錯誤信息顯示的位置
errorPlacement:Callback
指明錯誤放置的位置,默認情況是: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() ); }
代碼的作用是:一般情況下把錯誤信息顯示在 <td class="status"></td> 中,如果是 radio 則顯示在 <td></td> 中,如果是 checkbox 則顯示在內容的后面。
參數 類型 描述 默認值
errorClass String 指定錯誤提示的 css 類名,可以自定義錯誤提示的樣式。 "error"
errorElement String 用什么標簽標記錯誤,默認是 label,可以改成 em。 "label"
errorContainer Selector 顯示或者隱藏驗證信息,可以自動實現有錯誤信息出現時把容器屬性變為顯示,無錯誤時隱藏,用處不大。
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer Selector 把錯誤信息統一放在一個容器里面。
wrapper String 用什么標簽再把上邊的 errorELement 包起來。
一般這三個屬性同時使用,實現在一個容器內顯示所有錯誤提示的功能,并且沒有信息時自動隱藏。
errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"
5、更改錯誤信息顯示的樣式
設置錯誤提示的樣式,可以增加圖標顯示,在該系統中已經建立了一個 validation.css,專門用于維護校驗文件的樣式。
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; }
6、每個字段驗證通過執行函數
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"
7、驗證的觸發方式修改
下面的雖然是 boolean 型的,但建議除非要改為 false,否則別亂添加。
觸發方式 類型 描述 默認值
onsubmit Boolean 提交時驗證。設置為 false 就用其他方法去驗證。 true
onfocusout Boolean 失去焦點時驗證(不包括復選框/單選按鈕)。 true
onkeyup Boolean 在 keyup 時驗證。 true
onclick Boolean 在點擊復選框和單選按鈕時驗證。 true
focusInvalid Boolean 提交表單后,未通過驗證的表單(第一個或提交之前獲得焦點的未通過驗證的表單)會獲得焦點。 true
focusCleanup Boolean 如果是 true 那么當未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用。 false
// 重置表單 $().ready(function() { var validator = $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); $("#reset").click(function() { validator.resetForm(); }); });
8、異步驗證
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",不能有其他輸出。
9、添加自定義校驗
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)); }, "請正確填寫您的郵政編碼");
注意:要在 additional-methods.js 文件中添加或者在 jquery.validate.js 文件中添加。建議一般寫在 additional-methods.js 文件中。
注意:在 messages_cn.js 文件中添加:isZipCode: "只能包括中文字、英文字母、數字和下劃線"。調用前要添加對 additional-methods.js 文件的引用。
10、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表單驗證大全》 ,歡迎大家學習閱讀。
以上就是針對jQuery Validate表單驗證的深入學習,希望對大家的學習有所幫助。