天天看點

jQuery - Validate插件為表單提供強大的驗證功能 jQuery Validate

jQuery Validate

jQuery Validate 插件為表單提供了強大的驗證功能,讓用戶端表單驗證變得更簡單,同時提供了大量的定制選項,滿足應用程式各種需求。該插件捆綁了一套有用的驗證方法,包括 URL 和電子郵件驗證,同時提供了一個用來編寫使用者自定義方法的 API。所有的捆綁方法預設使用英語作為錯誤資訊,且已翻譯成其他 37 種語言。

該插件是由 Jörn Zaefferer 編寫和維護的,他是 jQuery 團隊的一名成員,是 jQuery UI 團隊的主要開發人員,是 QUnit 的維護人員。該插件在 2006 年 jQuery 早期的時候就已經開始出現,并一直更新至今。目前版本是 1.14.0 。

通路 jQuery Validate 官網 ,下載下傳最新版的 jQuery Validate 插件。

菜鳥教程提供的 1.14.0 版本下載下傳位址: http://static.runoob.com/download/jquery-validation-1.14.0.zip

導入 js 庫(使用菜鳥教程提供的CDN)

<scriptsrc="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script><scriptsrc="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>      

預設校驗規則

序号 規則 描述
1 required:true 必須輸入的字段。
2 remote:"check.php" 使用 ajax 方法調用 check.php 驗證輸入值。
3 email:true 必須輸入正确格式的電子郵件。
4 url:true 必須輸入正确格式的網址。
5 date:true 必須輸入正确格式的日期。日期校驗 ie6 出錯,慎用。
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。

預設提示

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.",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}.")}      

jQuery Validate提供了中文資訊提示包,位于下載下傳包的 dist/localization/messages_zh.js,内容如下:

(function(factory ){if(typeofdefine ==="function"&&define.amd ){define(["jquery","../jquery.validate"],factory );}else{factory(jQuery );}}(function($ ){/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: ZH (Chinese, 中文 (Zhōngwén), 漢語, 漢語)
 */$.extend($.validator.messages,{required:"這是必填字段",remote:"請修正此字段",email:"請輸入有效的電子郵件位址",url:"請輸入有效的網址",date:"請輸入有效的日期",dateISO:"請輸入有效的日期 (YYYY-MM-DD)",number:"請輸入有效的數字",digits:"隻能輸入數字",creditcard:"請輸入有效的信用卡号碼",equalTo:"你的輸入不相同",extension:"請輸入有效的字尾",maxlength:$.validator.format("最多可以輸入 {0} 個字元"),minlength:$.validator.format("最少要輸入 {0} 個字元"),rangelength:$.validator.format("請輸入長度在 {0} 到 {1} 之間的字元串"),range:$.validator.format("請輸入範圍在 {0} 到 {1} 之間的數值"),max:$.validator.format("請輸入不大于 {0} 的數值"),min:$.validator.format("請輸入不小于 {0} 的數值")});}));      

你可以将該本地化資訊檔案 dist/localization/messages_zh.js 引入到頁面:

<scriptsrc="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>      

使用方式

1、将校驗規則寫到控件中

<scriptsrc="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script><scriptsrc="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script><scriptsrc="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script><script>$.validator.setDefaults({submitHandler:function(){alert("送出事件!");}});$().ready(function(){$("#commentForm").validate();});</script><formclass="cmxform"id="commentForm"method="get"action=""><fieldset><legend>輸入您的名字,郵箱,URL,備注。</legend><p><labelfor="cname">Name (必需, 最小兩個字母)</label><inputid="cname"name="name"minlength="2"type="text"required></p><p><labelfor="cemail">E-Mail (必需)</label><inputid="cemail"type="email"name="email"required></p><p><labelfor="curl">URL (可選)</label><inputid="curl"type="url"name="url"></p><p><labelfor="ccomment">備注 (必需)</label><textareaid="ccomment"name="comment"required></textarea></p><p><inputclass="submit"type="submit"value="Submit"></p></fieldset></form>      

嘗試一下 »

2、将校驗規則寫到 js 代碼中

$().ready(function(){// 在鍵盤按下并釋放及送出後驗證送出表單$("#signupForm").validate({rules:{firstname:"required",lastname:"required",username:{required:true,minlength:2},password:{required:true,minlength:5},confirm_password:{required:true,minlength:5,equalTo:"#password"},email:{required:true,email:true},topic:{required:"#newsletter:checked",minlength:2},agree:"required"},messages:{firstname:"請輸入您的名字",lastname:"請輸入您的姓氏",username:{required:"請輸入使用者名",minlength:"使用者名必需由兩個字母組成"},password:{required:"請輸入密碼",minlength:"密碼長度不能小于 5 個字母"},confirm_password:{required:"請輸入密碼",minlength:"密碼長度不能小于 5 個字母",equalTo:"兩次密碼輸入不一緻"},email:"請輸入一個正确的郵箱",agree:"請接受我們的聲明",topic:"請選擇兩個主題"}});      

messages 處,如果某個控件沒有 message,将調用預設的資訊

<formclass="cmxform"id="signupForm"method="get"action=""><fieldset><legend>驗證完整的表單</legend><p><labelfor="firstname">名字</label><inputid="firstname"name="firstname"type="text"></p><p><labelfor="lastname">姓氏</label><inputid="lastname"name="lastname"type="text"></p><p><labelfor="username">使用者名</label><inputid="username"name="username"type="text"></p><p><labelfor="password">密碼</label><inputid="password"name="password"type="password"></p><p><labelfor="confirm_password">驗證密碼</label><inputid="confirm_password"name="confirm_password"type="password"></p><p><labelfor="email">Email</label><inputid="email"name="email"type="email"></p><p><labelfor="agree">請同意我們的聲明</label><inputtype="checkbox"class="checkbox"id="agree"name="agree"></p><p><labelfor="newsletter">我樂意接收新資訊</label><inputtype="checkbox"class="checkbox"id="newsletter"name="newsletter"></p><fieldsetid="newsletter_topics"><legend>主題 (至少選擇兩個) - 注意:如果沒有勾選“我樂意接收新資訊”以下選項會隐藏,但我們這裡作為示範讓它可見</legend><labelfor="topic_marketflash"><inputtype="checkbox"id="topic_marketflash"value="marketflash"name="topic">Marketflash</label><labelfor="topic_fuzz"><inputtype="checkbox"id="topic_fuzz"value="fuzz"name="topic">Latest fuzz</label><labelfor="topic_digester"><inputtype="checkbox"id="topic_digester"value="digester"name="topic">Mailing list digester</label><labelfor="topic"class="error">Please select at least two topics you'd like to receive.</label></fieldset><p><inputclass="submit"type="submit"value="送出"></p></fieldset></form>      

嘗試一下 »

required: true 值是必須的。 

required: "#aa:checked" 表達式的值為真,則需要驗證。 

required: function(){} 傳回為真,表示需要驗證。

後邊兩種常用于,表單中需要同時填或不填的元素。

常用方法及注意問題

1、用其他方式替代預設的 SUBMIT

$().ready(function(){$("#signupForm").validate({submitHandler:function(form){alert("送出事件!");form.submit();}});});      

使用 ajax 方式

$(".selector").validate({submitHandler:function(form){$(form).ajaxSubmit();}})      

可以設定 validate 的預設值,寫法如下:

$.validator.setDefaults({submitHandler:function(form){alert("送出事件!");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());}      

執行個體

<p>将錯誤資訊放在 label 元素後并使用 span 元素包裹它</p><formmethod="get"class="cmxform"id="form1"action=""><fieldset><legend>Login Form</legend><p><labelfor="user">Username</label><inputid="user"name="user"requiredminlength="3"></p><p><labelfor="password">Password</label><inputid="password"type="password"maxlength="12"name="password"requiredminlength="5"></p><p><inputclass="submit"type="submit"value="Login"></p></fieldset></form>      

嘗試一下 »

代碼的作用是:一般情況下把錯誤資訊顯示在 <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:1pxsolid red;}label.error {background:url("./demo/images/unchecked.gif")no-repeat 0px0px;padding-left:16px;padding-bottom:2px;font-weight:bold;color:#EA5200;}label.checked{background:url("./demo/images/checked.gif")no-repeat 0px0px;}      

6、每個字段驗證通過執行函數

success:String,Callback      

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

success:function(label){// set &nbsp; as text for IElabel.html("&nbsp;").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(){varvalidator =$("#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){varlength =value.length;for(vari =0;i <value.length;i++){if(value.charCodeAt(i)>127){length++;}}returnthis.optional(element)||(length >=param[0]&&length <=param[1]);},$.validator.format("請確定輸入的值在{0}-{1}個位元組之間(一個中文字算2個位元組)"));// 郵政編碼驗證   jQuery.validator.addMethod("isZipCode",function(value,element){vartel =/^[0-9]{6}$/;returnthis.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 表示必須選中一個。

<inputtype="radio"id="gender_male"value="m"name="gender"class="{required:true}"/><inputtype="radio"id="gender_female"value="f"name="gender"/>      

checkbox 的 required 表示必須選中。

<inputtype="checkbox"class="checkbox"id="agree"name="agree"class="{required:true}"/>      

checkbox 的 minlength 表示必須選中的最小個數,maxlength 表示最大的選中個數,rangelength:[2,3] 表示選中個數區間。

<inputtype="checkbox"class="checkbox"id="spam_email"value="email"name="spam[]"class="{required:true, minlength:2}"/><inputtype="checkbox"class="checkbox"id="spam_phone"value="phone"name="spam[]"/><inputtype="checkbox"class="checkbox"id="spam_mail"value="mail"name="spam[]"/>      

select 的 required 表示選中的 value 不能為空。

<selectid="jungle"name="jungle"title="Please select something!"class="{required:true}"><optionvalue=""></option><optionvalue="1">Buga</option><optionvalue="2">Baga</option><optionvalue="3">Oi</option></select>      

select 的 minlength 表示選中的最小個數(可多選的 select),maxlength 表示最大的選中個數,rangelength:[2,3] 表示選中個數區間。

<selectid="fruit"name="fruit"title="Please select at least two fruits"class="{required:true, minlength:2}"multiple="multiple"><optionvalue="b">Banana</option><optionvalue="a">Apple</option><optionvalue="p">Peach</option><optionvalue="t">Turtle</option></select>      

jQuery.validate 中文 API

名稱 傳回類型 描述
validate(options) Validator 驗證所選的 FORM。
valid() Boolean 檢查是否驗證通過。
rules() Options 傳回元素的驗證規則。
rules("add",rules) Options 增加驗證規則。
rules("remove",rules) Options 删除驗證規則。
removeAttrs(attributes) Options 删除特殊屬性并且傳回它們。
自定義選擇器
:blank Validator 沒有值的篩選器。
:filled Array <Element> 有值的篩選器。
:unchecked Array <Element> 沒選擇的元素的篩選器。
實用工具
jQuery.format(template,argument,argumentN...) String 用參數代替模闆中的 {n}。

Validator

validate 方法傳回一個 Validator 對象。Validator 對象有很多方法可以用來引發校驗程式或者改變 form 的内容,下面列出幾個常用的方法。

名稱 傳回類型 描述
form() Boolean 驗證 form 傳回成功還是失敗。
element(element) Boolean 驗證單個元素是成功還是失敗。
resetForm() undefined 把前面驗證的 FORM 恢複到驗證前原來的狀态。
showErrors(errors) undefined 顯示特定的錯誤資訊。
Validator 函數
setDefaults(defaults) undefined 改變預設的設定。
addMethod(name,method,message) undefined 添加一個新的驗證方法。必須包括一個獨一無二的名字,一個 JAVASCRIPT 的方法和一個預設的資訊。
addClassRules(name,rules) undefined 增加組合驗證類型,在一個類裡面用多種驗證方法時比較有用。
addClassRules(rules) undefined 增加組合驗證類型,在一個類裡面用多種驗證方法時比較有用。這個是同時加多個驗證方法。

内置驗證方式

名稱 傳回類型 描述
required() Boolean 必填驗證元素。
required(dependency-expression) Boolean 必填元素依賴于表達式的結果。
required(dependency-callback) Boolean 必填元素依賴于回調函數的結果。
remote(url) Boolean 請求遠端校驗。url 通常是一個遠端調用方法。
minlength(length) Boolean 設定最小長度。
maxlength(length) Boolean 設定最大長度。
rangelength(range) Boolean 設定一個長度範圍 [min,max]。
min(value) Boolean 設定最小值。
max(value) Boolean 設定最大值。
email() Boolean 驗證電子郵箱格式。
range(range) Boolean 設定值的範圍。
url() Boolean 驗證 URL 格式。
date() Boolean 驗證日期格式(類似 30/30/2008 的格式,不驗證日期準确性隻驗證格式)。
dateISO() Boolean 驗證 ISO 類型的日期格式。
dateDE() Boolean 驗證德式的日期格式(29.04.1994 或 1.1.2006)。
number() Boolean 驗證十進制數字(包括小數的)。
digits() Boolean 驗證整數。
creditcard() Boolean 驗證信用卡号。
accept(extension) Boolean 驗證相同字尾名的字元串。
equalTo(other) Boolean 驗證兩個輸入框的内容是否相同。
phoneUS() Boolean 驗證美式的電話号碼。

validate ()的可選項

描述 代碼
debug:進行調試模式(表單不送出)。
$(".selector").validate({debug:true})      
把調試設定為預設。
$.validator.setDefaults({debug:true})      
submitHandler:通過驗證後運作的函數,裡面要加上表單送出的函數,否則表單不會送出。
$(".selector").validate({submitHandler:function(form){$(form).ajaxSubmit();}})      
ignore:對某些元素不進行驗證。
$("#myform").validate({ignore:".ignore"})      
rules:自定義規則,key:value 的形式,key 是要驗證的元素,value 可以是字元串或對象。
$(".selector").validate({rules:{name:"required",email:{required:true,email:true}}})      
messages:自定義的提示資訊,key:value 的形式,key 是要驗證的元素,value 可以是字元串或函數。
$(".selector").validate({rules:{name:"required",email:{required:true,email:true}},messages:{name:"Name不能為空",email:{required:"E-mail不能為空",email:"E-mail位址不正确"}}})      
groups:對一組元素的驗證,用一個錯誤提示,用 errorPlacement 控制把出錯資訊放在哪裡。
$("#myform").validate({groups:{username:"fname 
		lname"},errorPlacement:function(error,element){if(element.attr("name")=="fname"||element.attr("name")=="lname")error.insertAfter("#lastname");elseerror.insertAfter(element);},debug:true})      
OnSubmit:類型 Boolean,預設 true,指定是否送出時驗證。
$(".selector").validate({onsubmit:false})      
onfocusout:類型 Boolean,預設 true,指定是否在擷取焦點時驗證。
$(".selector").validate({onfocusout:false})      
onkeyup:類型 Boolean,預設 true,指定是否在敲擊鍵盤時驗證。
$(".selector").validate({onkeyup:false})      
onclick:類型 Boolean,預設 true,指定是否在滑鼠點選時驗證(一般驗證 checkbox、radiobox)。
$(".selector").validate({onclick:false})      
focusInvalid:類型 Boolean,預設 true。送出表單後,未通過驗證的表單(第一個或送出之前獲得焦點的未通過驗證的表單)會獲得焦點。
$(".selector").validate({focusInvalid:false})      
focusCleanup:類型 Boolean,預設 false。當未通過驗證的元素獲得焦點時,移除錯誤提示(避免和 focusInvalid 一起使用)。
$(".selector").validate({focusCleanup:true})      
errorClass:類型 String,預設 "error"。指定錯誤提示的 css 類名,可以自定義錯誤提示的樣式。
$(".selector").validate({errorClass:"invalid"})      
errorElement:類型 String,預設 "label"。指定使用什麼标簽标記錯誤。
$(".selector").validate
   errorElement:"em"})      
wrapper:類型 String,指定使用什麼标簽再把上邊的 errorELement 包起來。
$(".selector").validate({wrapper:"li"})      
errorLabelContainer:類型 Selector,把錯誤資訊統一放在一個容器裡面。
$("#myform").validate({errorLabelContainer:"#messageBox",wrapper:"li",submitHandler:function(){alert("Submitted!")}})      
showErrors:跟一個函數,可以顯示總共有多少個未通過驗證的元素。
$(".selector").validate({showErrors:function(errorMap,errorList){$("#summary").html("Your form contains "+this.numberOfInvalids()+" errors,see details below.");this.defaultShowErrors();}})      
errorPlacement:跟一個函數,可以自定義錯誤放到哪裡。
$("#myform").validate({errorPlacement:function(error,element){error.appendTo(element.parent("td").next("td"));},debug:true})      
success:要驗證的元素通過驗證後的動作,如果跟一個字元串,會當作一個 css 類,也可跟一個函數。
$("#myform").validate({success:"valid",submitHandler:function(){alert("Submitted!")}})      
highlight:可以給未通過驗證的元素加效果、閃爍等。

addMethod(name,method,message)方法

參數 name 是添加的方法的名字。

參數 method 是一個函數,接收三個參數 (value,element,param) 。 

value 是元素的值,element 是元素本身,param 是參數。

我們可以用 addMethod 來添加除内置的 Validation 方法之外的驗證方法。比如有一個字段,隻能輸一個字母,範圍是 a-f,寫法如下:

$.validator.addMethod("af",function(value,element,params){if(value.length>1){returnfalse;}if(value>=params[0]&&value<=params[1]){returntrue;}else{returnfalse;}},"必須是一個字母,且a-f");      

如果有個表單字段的 id="username",則在 rules 中寫:

username:{af:["a","f"]}      

addMethod 的第一個參數,是添加的驗證方法的名字,這時是 af。 

addMethod 的第三個參數,是自定義的錯誤提示,這裡的提示為:"必須是一個字母,且a-f"。 

addMethod 的第二個參數,是一個函數,這個比較重要,決定了用這個驗證方法時的寫法。

如果隻有一個參數,直接寫,比如 af:"a",那麼 a 就是這個唯一的參數,如果多個參數,則寫在 [] 裡,用逗号分開。

meta String 方式

$("#myform").validate({meta:"validate",submitHandler:function(){alert("Submitted!")}})      
<scripttype="text/javascript"src="js/jquery.metadata.js"></script><scripttype="text/javascript"src="js/jquery.validate.js"></script><formid="myform"><inputtype="text"name="email"class="{validate:{ required:true,email:true }}"/><inputtype="submit"value="Submit"/></form>