jQuery Validate表單驗證深入學(xué)習(xí)
之前一篇文章介紹了jQuery Validate表單驗證入門的基礎(chǔ)知識,詳細內(nèi)容參見《jQuery Validate表單驗證入門學(xué)習(xí)》,今天這篇文章深入學(xué)習(xí)jQuery Validate表單驗證,以下就是文章的全部內(nèi)容:
1、用其他方式替代默認的 SUBMIT
$().ready(function() { $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); });
使用 ajax 方式
$(".selector").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } })
可以設(shè)置 validate 的默認值,寫法如下:
$.validator.setDefaults({ submitHandler: function(form) { alert("submitted!");form.submit(); } });
如果想提交表單, 需要使用 form.submit(),而不要使用 $(form).submit()。
2、debug,只驗證不提交表單
如果這個參數(shù)為true,那么表單不會提交,只進行檢查,調(diào)試時十分方便。
$().ready(function() { $("#signupForm").validate({ debug:true }); });
如果一個頁面中有多個表單都想設(shè)置成為 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 則顯示在內(nèi)容的后面。
參數(shù) 類型 描述 默認值
errorClass String 指定錯誤提示的 css 類名,可以自定義錯誤提示的樣式。 "error"
errorElement String 用什么標(biāo)簽標(biāo)記錯誤,默認是 label,可以改成 em。 "label"
errorContainer Selector 顯示或者隱藏驗證信息,可以自動實現(xiàn)有錯誤信息出現(xiàn)時把容器屬性變?yōu)轱@示,無錯誤時隱藏,用處不大。
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer Selector 把錯誤信息統(tǒng)一放在一個容器里面。
wrapper String 用什么標(biāo)簽再把上邊的 errorELement 包起來。
一般這三個屬性同時使用,實現(xiàn)在一個容器內(nèi)顯示所有錯誤提示的功能,并且沒有信息時自動隱藏。
errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"
5、更改錯誤信息顯示的樣式
設(shè)置錯誤提示的樣式,可以增加圖標(biāo)顯示,在該系統(tǒng)中已經(jīng)建立了一個 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、每個字段驗證通過執(zhí)行函數(shù)
success:String,Callback
要驗證的元素通過驗證后的動作,如果跟一個字符串,會當(dāng)作一個 css 類,也可跟一個函數(shù)。
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、驗證的觸發(fā)方式修改
下面的雖然是 boolean 型的,但建議除非要改為 false,否則別亂添加。
觸發(fā)方式 類型 描述 默認值
onsubmit Boolean 提交時驗證。設(shè)置為 false 就用其他方法去驗證。 true
onfocusout Boolean 失去焦點時驗證(不包括復(fù)選框/單選按鈕)。 true
onkeyup Boolean 在 keyup 時驗證。 true
onclick Boolean 在點擊復(fù)選框和單選按鈕時驗證。 true
focusInvalid Boolean 提交表單后,未通過驗證的表單(第一個或提交之前獲得焦點的未通過驗證的表單)會獲得焦點。 true
focusCleanup Boolean 如果是 true 那么當(dāng)未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用。 false
// 重置表單 $().ready(function() { var validator = $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); $("#reset").click(function() { validator.resetForm(); }); });
8、異步驗證
remote:URL
使用 ajax 方式進行驗證,默認會提交當(dāng)前驗證的值到遠程地址,如果需要提交其他的值,可以使用 data 選項。
remote: "check-email.php" remote: { url: "check-email.php", //后臺處理程序 type: "post", //數(shù)據(jù)發(fā)送方式 dataType: "json", //接受數(shù)據(jù)格式 data: { //要傳遞的數(shù)據(jù) username: function() { return $("#username").val(); } } }
遠程地址只能輸出 "true" 或 "false",不能有其他輸出。
9、添加自定義校驗
addMethod:name, method, message
自定義驗證方法
// 中文字兩個字節(jié) 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}個字節(jié)之間(一個中文字算2個字節(jié))")); // 郵政編碼驗證 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: "只能包括中文字、英文字母、數(shù)字和下劃線"。調(diào)用前要添加對 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 表示必須選中的最小個數(shù),maxlength 表示最大的選中個數(shù),rangelength:[2,3] 表示選中個數(shù)區(qū)間。 <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 表示選中的最小個數(shù)(可多選的 select),maxlength 表示最大的選中個數(shù),rangelength:[2,3] 表示選中個數(shù)區(qū)間。 <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>
附表:內(nèi)置驗證方式:
本文已被整理到了《jquery表單驗證大全》 ,歡迎大家學(xué)習(xí)閱讀。
以上就是針對jQuery Validate表單驗證的深入學(xué)習(xí),希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
jQuery發(fā)請求傳輸中文參數(shù)亂碼問題的解決方案
這篇文章主要介紹了jQuery發(fā)請求傳輸中文參數(shù)亂碼問題的解決方案,需要的朋友可以參考下2018-05-05jQuery 1.4 15個你應(yīng)該知道的新特性(譯)
jQuery 1.4 最近剛剛發(fā)布. 這個版本可不是一個簡單的改進,它不僅包含了很多新的特性,還改進了很多功能, 更在性能優(yōu)化方面下了很大功夫, 本文將對這些新的特性和增強的部分進行討論,希望能對你有所幫助.2010-01-01jQuery實現(xiàn)表單動態(tài)添加數(shù)據(jù)并提交的方法
這篇文章主要介紹了jQuery實現(xiàn)表單動態(tài)添加數(shù)據(jù)并提交的方法,結(jié)合實例形式總結(jié)分析了jQuery針對存在form表單的添加、提交,不存在form表單的添加、提交,ajax、非ajax形式提交等數(shù)據(jù)添加與表單提交操作技巧,需要的朋友可以參考下2018-07-07用示例說明filter()與find()的用法以及children()與find()的區(qū)別分析
本篇文章介紹了,用示例說明filter()與find()的用法以及children()與find()的區(qū)別分析。需要的朋友參考下2013-04-04