歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery表單校驗jquery.validate.js的使用

jQuery表單校驗jquery.validate.js的使用

日期:2017/3/1 11:16:29   编辑:Linux編程

jQuery是一個快速、簡潔的js庫,為網站的快速開發簡化了HTML文檔遍歷,事件處理,動畫,以及Ajax交互。使用jQuery將極大的提高編寫javascript代碼的效率, 讓寫出來的代碼更加優雅, 更加健壯。

jquery.validate.js是jquery旗下的一個驗證框架,借助jquery的優勢,我們可以迅速驗證一些常見的輸入,並且可以自己擴充自己的驗證方法

1.jquery包的引入:

引入jquery包:<script type="text/javascript" src="/common/js/jquery/jquery.js'"></script>

2.添加校驗說明:

主要使用的是javascript編寫的驗證庫——jQuery.Validate,這個驗證庫是屬於jQuery的插件。

引入:

<script type="text/javascript" src="/common/js/jquery/jquery.validate.pack.js"></script>

jQuery.Validate是監控form的,在任何提交表單的操作前jQuery.Validate都會檢測表單裡的輸入項是否滿足規則,滿足才允許提交。所以需要在jQuery(document).ready()時為form進行驗證注冊,格式: $(“#formid”).validate(jsonobj)。

其中formid是文件中form表單的id,jsonobj包含兩個屬性:rules和messages,rules用來指明每個字段上添加的校驗規則,messages用來說明相應的校驗出錯時對應的提示語。

messages為非必須,如果自己不定義該屬性,會采用默認的提示。

例如/test/validate/formvalidate.jsp:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<title>表單校驗</title>

<script type="text/javascript" src="/common/jquery.js"></script>

<script type="text/javascript" src="/common/jquery.validate.pack.js"></script>

<script type="text/javascript" src="/common/jquery.form.js"></script>

</head>

<body>

<form id="test">

<input name="nameput" type="text" size="20"/>

<input name="submit" type="submit" value="提交"/>

</form>

<script type="text/javascript">

$("#test").validate({

rules:{

"nameput":{

required:true,

minlength:3,

maxlength:10

}

},

messages:{

"nameput":{

required:"不能為空",

minlength:jQuery.format("長度不小於{0}"),

maxlength:jQuery.format("長度不大於{0}")

}

}

})

</script>

</body>

</html>

注意:nameput是input標簽的name。

Required、minlength、maxlength都是jQuery校驗的內置驗證方式。jQuery內置驗證方式參考jQuery.validate.js的API。

3.自定義驗證方式

下面是自定義的驗證方式:

$.validator.addMethod("stringlength", function(value, element,params) {

//默認值 : {trim:true,minLength:-1,maxLength:-1

params = $.extend([true,-1,-1],params); //對於默認參數支持

if(params[0]){ //過濾首尾空格

value=$.trim(value);

}

value = value.replace(/<(?:.)*?>/g,""); //驗證時過濾標簽

return this.optional(element) || ((params[1]<0 || value.length>=params[1])&&(params[2]<0 || value.length<=params[2]));

}, jQuery.format("長度在{1}-{2}之間"));

例如home工程中的登錄校驗:

$('#loginform').validate({//登陸校驗

rules:{

"userAccount.userName":{

"requiredstring":["true"],

" requiredstring ":true,

"stringlength":["true","3","40"]

},

"userAccount.userPwd":{

"requiredstring":["true"],

"stringlength":["true","1","20"]

}

},

messages:{

"userAccount.userName":{

"requiredstring":"用戶名必填",

"stringlength":jQuery.format("用戶名長度在{1}和{2}之間")

},

"userAccount.userPwd":{

"requiredstring":"密碼不可以為空",

"stringlength":jQuery.format("密碼長度在{1}和{2}之間")

}

}

})

userAccount.userName是頁面對應的input的name,requiredstring、requiredstring、stringlength是自己定義的校驗,定義在/image/hi/common/js/zxwvalidate.js裡。

{1}、{2}等是rules裡面對應驗證方式的第幾個元素,從0開始。

簡單的實例:

$.validator.addMethod("twd", function(value, element,params) { //默認值 : {trim:true,minLength:-1,maxLength:-1

params = $.extend([true,-1,-1],params); //對於默認參數支持

if(params[0]){

value=$.trim(value);

}

})

$("#test").validate({

rules:{

"nameput":{

"twd":[true,3,10]

}

},

messages:{

"nameput":{

"twd":jQuery.format("長度在{1}和{2}之間")

}

}

})

4.其他注意事項

(1)校驗默認是在點擊提交submit的時候起作用.

(2)如果缺少$().ready(function() { }),校驗內容必須寫在表單的後面。

(3)debug方法需要單獨寫或者rules和messages的後面,否則不會起作用。

附:

jQuery.Validate為我們提供了3種驗證編寫方式,各有優缺點:

(1)在input對象中書寫class樣式指定驗證規則或屬性驗證規則:

如<input type=”text” class=”required”/>

最簡單、最便捷,提示消息使用jQuery.Validate的內置的消息(自定義擴展驗證規則也屬於此項),但是由於是以樣式名的方式進行驗證,導致了日後修改必須找到相應的input對象,同時無法使用高級驗證規則。

(2)在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腳本,但好處是可以統一驗證規范,將每個頁面的驗證規則都寫在頭部的腳本中,方便日後維護

默認的提示

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).",
dateDE: "Bitte geben Sie ein g眉ltiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
digits: "Please enter only digits",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
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}.")
}

Copyright © Linux教程網 All Rights Reserved