validate插件是一個基于jquery的表單驗證插件了里面有許多的常用的一些驗證方法我們可以直接調用,具體的我們一起來看看。
例子,html代碼
<!DOCTYPE html><html lang="en"><head><include file="Common/Header" /><meta charset="utf-8"><script src="/jquery.min.js"></script></head><body><form class="form-horizontal" id="form" onsubmit="return false;"><input type="text" name="password_old" class="form-control required" id="password_old" maxlength="20"><input type="password" name="pay_password" class="form-control required" id="pay_password"><input type="password" name="password_Repeat" class="form-control required" id="password_Repeat"><button type="submit" id="submit" class="btn btn-success btn-padding-lr-30 margin-right-15">確定</button></form></body><!-------------------------------------------------------------------------><script src="jquery.validate.min.js"></script><script src="messages_cn.js"></script><script type="text/javascript">$(document).ready(function(){//提交$('#submit').click(function(){var pay_password = $('#pay_password').val();var password_Repeat = $('#password_Repeat').val();var password_old = $('#password_old').val(); var data = {'pay_password':pay_password,'password_Repeat':password_Repeat,'password_old':password_old};console.info(data);var v = $('#form').validate({rules : {pay_password : {required : true,minlength : 6,ismypassword : true},password_Repeat : {required : true,minlength : 6,ismypassword : true},password_old : {required : true,minlength : 6,}},messages : {pay_password : {required : "請輸入密碼",minlength : "字符長度不能小于6個字符",ismypassword : "密碼必須由數字、英文字母和特殊字符(!,.@#$%^&*?_~)組成"},password_Repeat : {required : "請輸入密碼",minlength : "字符長度不能小于6個字符",ismypassword : "密碼必須由數字、英文字母和特殊字符(!,.@#$%^&*?_~)組成"},password_old : {required : "請輸入密碼",minlength : "字符長度不能小于6個字符",},}});if(pay_password != password_Repeat){alert("密碼不一致,請重新輸入確認!");return false;}//---------------------------------if(!v.form())return false;$.ajax({url:'{:U("Merchant/ajax_pw")}',data: data,beforeSend:function(){},success:function(res){ if(res == 1){alert("密碼修改成功");}if(res == 0){alert("兩次密碼一樣,未做修改");} if(res != 0 && res != 1){alert(res);} }});//------------------------});})</script></html>
messages_cn.js文件如下
jQuery.extend(jQuery.validator.messages, {required: "必選字段",remote: "請修正該字段",email: "請輸入正確格式的電子郵件",url: "請輸入合法的網址",date: "請輸入合法的日期",dateISO: "請輸入合法的日期 (ISO).",number: "請輸入合法的數字",digits: "只能輸入整數",creditcard: "請輸入合法的信用卡號",equalTo: "請再次輸入相同的值",accept: "請輸入擁有合法后綴名的字符串",maxlength: jQuery.validator.format("請輸入一個 長度最多是 {0} 的字符串"),minlength: jQuery.validator.format("請輸入一個 長度最少是 {0} 的字符串"),rangelength: jQuery.validator.format("請輸入 一個長度介于 {0} 和 {1} 之間的字符串"),range: jQuery.validator.format("請輸入一個介于 {0} 和 {1} 之間的值"),max: jQuery.validator.format("請輸入一個最大為{0} 的值"),min: jQuery.validator.format("請輸入一個最小為{0} 的值")});
關于validator插件詳解
主要分幾部分
jquery.validate 基本用法
jquery.validate API說明
jquery.validate 自定義
jquery.validate 常見類型的驗證代碼
下載地址
jquery.validate插件的文檔地址
http://docs.jquery.com/Plugins/Validation
jquery.validate插件的主頁
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
jquery.validate插件主頁上提供的demo
http://jquery.bassistance.de/validate/demo/
驗證規則
下面是默認校驗規則,也可以自定義規則
(1)required:true 必輸字段
(2)remote:"check.php" 使用ajax方法調用check.php驗證輸入值
(3)email:true 必須輸入正確格式的電子郵件
(4)url:true 必須輸入正確格式的網址
(5)date:true 必須輸入正確格式的日期
(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
驗證提示
下面是默認的驗證提示,官網有簡體中文版的驗證提示下載,或者通過jQuery.extend(jQuery.validator.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.",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}.")
使用方式
1:
在控件中使用默認驗證規則,例子:
電子郵件(必填)
<input id="email" class="required email" value="email@" />
2:
可以在控件中自定義驗證規則,例子:
自定義(必填,[3,5])
<input id="complex" value="hi" class="{required:true,minlength:3, maxlength:5,messages:{required:'為什么不輸入一點文字呢',minlength:'輸入的太少了',maxlength:'輸入那么多干嘛'}}" />
3:
通過javascript自定義驗證規則,下面的JS自定義了兩個規則,password和confirm_password
$().ready(function() {$("#form2").validate({rules: {password: {required: true,minlength: 5},confirm_password: {required: true,minlength: 5,equalTo: "#password"}},messages: {password: {required: "沒有填寫密碼",minlength: jQuery.format("密碼不能小于{0}個字符")},confirm_password: {required: "沒有確認密碼",minlength: "確認密碼不能小于{0}個字符",equalTo: "兩次輸入密碼不一致嘛"}}});});
required除了設置為true/false之外,還可以使用表達式或者函數,比如
$("#form2").validate({rules: {funcvalidate: {required: function() {return $("#password").val()!=""; }}},messages: {funcvalidate: {required: "有密碼的情況下必填"}}});
Html
密碼<input id="password" name="password" type="password" />確認密碼<input id="confirm_password" name="confirm_password" type="password" />條件驗證<input id="funcvalidate" name="funcvalidate" value="" />
4:
使用meta自定義驗證信息
首先用JS設置meta
$("#form3").validate({ meta: "validate" });
Html
email<input class="{validate:{required:true, email:true,messages:{required:'輸入email地址', email:'你輸入的不是有效的郵件地址'}}}"/>
5:
使用meta可以將驗證規則寫在自定義的標簽內,比如validate
JS設置meta
$().ready(function() {$.metadata.setType("attr", "validate");$("#form1").validate();});
Html
<input id="email" name="email"validate="{required:true, email:true, messages:{required:'輸入email地址', email:'你輸入的不是有效的郵件地址'}}" />
6:
自定義驗證規則
對于復雜的驗證,可以通過jQuery.validator.addMethod添加自定義的驗證規則
官網提供的additional-methods.js里包含一些常用的驗證方式,比如lettersonly,ziprange,nowhitespace等
例子
// 字符驗證 jQuery.validator.addMethod("userName", function(value, element) {return this.optional(element) || /^[/u0391-/uFFE5/w]+$/.test(value);}, "用戶名只能包括中文字、英文字母、數字和下劃線"); //然后就可以使用這個規則了$("#form1").validate({// 驗證規則rules: {userName: {required: true,userName: true,rangelength: [5,10]}},/* 設置錯誤信息 */messages: {userName: {required: "請填寫用戶名",rangelength: "用戶名必須在5-10個字符之間"} },});
7:
radio、checkbox、select的驗證方式類似
radio的驗證
性別
<span>男<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}"/><br />女<input type="radio" id="gender_female" value="f" name="gender" /></span>
checkbox的驗證
最少選擇兩項
<span>選項1<input type="checkbox" id="check_1" value="1" name="checkGroup"class="{required:true,minlength:2, messages:{required:'必須選擇',minlength:'至少選擇2項'}}" /><br />選項2<input type="checkbox" id="check_2" value="2" name="checkGroup" /><br />選項3<input type="checkbox" id="check_3" value="3" name="checkGroup" /><br /></span>
select的驗證
下拉框
<span><select id="selectbox" name="selectbox" class="{required:true}"><option value=""></option><option value="1">1</option><option value="2">2</option><option value="3">3</option></select></span>
8:
Ajax驗證
用remote可以進行Ajax驗證
remote: {url: "url", //url地址type: "post", //發送方式dataType: "json", //數據格式 data: { //要傳遞的數據username: function() {return $("#username").val();}}}
Plugin methods
Name Type
validate( options ) Returns: Validator
驗證所選的FORM
valid( ) Returns: Boolean
檢查是否驗證通過
rules( ) Returns: Options
返回元素的驗證規則
rules( "add", rules ) Returns: Options
增加驗證規則
rules( "remove", rules ) Returns: Options
刪除驗證規則
removeAttrs( attributes ) Returns: Options
刪除特殊屬性并且返回他們
Custom selectors
Name Type
:blank Returns: Array <Element >
沒有值的篩選器
:filled Returns: Array <Element >
有值的篩選器
:unchecked Returns: Array <Element >
沒選擇的元素的篩選器
Utilities
Name Type
jQuery.format( template, argument , argumentN... ) Returns: String
用參數代替模板中的 {n}。
Validator
validate方法返回一個Validator對象, 它有很多方法, 讓你能使用引發校驗程序或者改變form的內容.
下面只是列出常用的.
form( ) Returns: Boolean
驗證form返回成功還是失敗
element( element ) Returns: Boolean
驗證單個元素是成功還是失敗
resetForm( ) Returns: undefined
把前面驗證的FORM恢復到驗證前原來的狀態
showErrors( errors ) Returns: undefined
顯示特定的錯誤信息
built-in Validation methods
Name Type
setDefaults( defaults ) Returns: undefined
改變默認的設置
addMethod( name, method, message ) Returns: undefined
添加一個新的驗證方法. 必須包括名字,一個JAVASCRIPT方法和一個默認的信息
addClassRules( name, rules ) Returns: undefined
增加組合驗證類型
addClassRules( rules ) Returns: undefined
增加組合驗證類型
built-in Validation methods
Name Type
required( ) Returns: Boolean
必填驗證元素
required( dependency-expression ) Returns: Boolean
必填元素依賴于表達式的結果.
required( dependency-callback ) Returns: Boolean
必填元素依賴于回調函數的結果.
remote( url ) Returns: Boolean
請求遠程校驗。url通常是一個遠程調用方法
minlength( length ) Returns: Boolean
設置最小長度
maxlength( length ) Returns: Boolean
設置最大長度
rangelength( range ) Returns: Boolean
設置一個長度范圍[min,max]
min( value ) Returns: Boolean
設置最小值.
max( value ) Returns: Boolean
設置最大值.
range( range ) Returns: Boolean
設置值的范圍
email( ) Returns: Boolean
驗證電子郵箱格式
url( ) Returns: Boolean
驗證連接格式
date( ) Returns: Boolean
驗證日期格式(類似30/30/2008的格式,不驗證日期準確性只驗證格式)
dateISO( ) Returns: Boolean
研制ISO類型的日期格式
dateDE( ) Returns: Boolean
驗證德式的日期格式(29.04.1994 or 1.1.2006)
number( ) Returns: Boolean
驗證十進制數字(包括小數的)
numberDE( ) Returns: Boolean
Makes the element require a decimal number with german format.
digits( ) Returns: Boolean
驗證整數
creditcard( ) Returns: Boolean
驗證信用卡號
accept( extension ) Returns: Boolean
驗證相同后綴名的字符串
equalTo( other ) Returns: Boolean
驗證兩個輸入框的內容是否相同
自定義jquery-validate的驗證行為
1: 自定義表單提交
設置submitHandler來自定義表單提交動作
$(".selector").validate({submitHandler: function(form) { alert("驗證通過"); }});
如果需要提交表單,可以調用
form.submit(); 或者$(form).ajaxSubmit();
2: 調試模式
將debug設置為true,表單不會提交,只進行檢查,方便調試
$(".selector").validate({debug: true})
3: 設置validate的默認值
使用setDefaults可以設置validate的默認值,比如默認所有表單驗證都是在debug模式下進行
$.validator.setDefaults({debug: true})
4: 某些元素不驗證
設置ignore屬性可以忽略某些元素不驗證
$(".selector").validate({ignore: "ignore"})
5: 驗證時機
jquery.validate可以很方便的設置在什么時候觸發驗證動作
onsubmit: 提交時是否驗證
$(".selector").validate({onsubmit: false})
onfocusout: 失去焦點時驗證(checkboxes/radio除外)
$(".selector").validate({onfocusout: false})
onkeyup: 在keyup時驗證
$(".selector").validate({onkeyup: false})
onclick: 在checkboxes、radio點擊時驗證.
$(".selector").validate({onclick: false})
6: 重寫驗證規則和驗證提示信息
//重寫max的的驗證提示信息$.validator.messages.max = jQuery.format("Your totals musn't exceed {0}!");//重寫equal方法$.validator.methods.equal = function(value, element, param) {return value == param;};
7: focusInvalid 是否把焦點聚焦在最后一個動作或者最近的一次出錯上
$(".selector").validate({focusInvalid: false})
8: focusCleanup
如果該屬性設置為True, 那么控件獲得焦點時,移除出錯的class定義,隱藏錯誤信息,避免和 focusInvalid.一起用。
$(".selector").validate({focusCleanup: true})
9: meta
設置meta來封裝驗證規則
$(".selector").validate({meta: "validate",})<script type="text/javascript"></script>
自定義錯誤消息的顯示方式
默認情況下,驗證提示信息用label元素來顯示, 并且會添加css class, 通過css可以很方便設置出錯控件以及錯誤信息的顯示方式。
/* 輸入控件驗證出錯*/form input.error { border:solid 1px red;}/* 驗證錯誤提示信息*/form label.error{width: 200px;margin-left: 10px; color: Red;}
如果想自定義顯示方式,可以修改jquery.validate的默認顯示方式
默認用label顯示錯誤消息,可以通過errorElement屬性來修改
errorElement: 錯誤消息的html標簽
$(".selector").validateerrorElement: "em"})
可以在出錯信息外用其他的元素包裝一層。
wrapper: 錯誤消息的外層封裝html標簽
$(".selector").validate({wrapper: "li"})
驗證出錯的css class默認是error,通過errorClass可以修改
errorClass: 驗證出錯時使用的css class
$(".selector").validate({errorClass: "invalid"})
還自定義驗證成功時的動作
success: 如果值是字符串,會當做一個css類,如果是一個函數,則執行該函數
$(".selector").validate({success: "valid"})
或者
success: function(label) {label.html(" ").addClass("checked");}
還可以把錯誤消息統一到一個容器顯示
errorLabelContainer: 將錯誤消息統一到一個容器顯示
$("#myform").validate({errorLabelContainer: "#messageBox"})
默認情況下,錯誤消息是放在驗證元素后面的,可以自定義錯誤消息的顯示位置
$(".selector").validate({errorPlacement: function(error, element) {error.appendTo( element.parent("td").next("td") );}})
更進一步可以定義一個組,把幾個地方的出錯信息統一放在一個地方,用error Placement控制把出錯信息放在哪里
groups:定義一個組
$(".selector").validate({groups: {username: "fname lname"},errorPlacement: function(error, element) {if (element.attr("name") == "fname" || element.attr("name") == "lname" )error.insertAfter("#lastname");elseerror.insertAfter(element);}})
高亮顯示
highlight: 高亮顯示,默認是添加errorClass
unhighlight: 和highlight對應,反高亮顯示
$(".selector").validate({highlight: function(element, errorClass) {$(element).addClass(errorClass);$(element.form).find("label[for=" + element.id + "]").addClass(errorClass);},unhighlight: function(element, errorClass) {$(element).removeClass(errorClass);$(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);}});
或者可以完全自定義錯誤顯示
showErrors: 得到錯誤的顯示句柄
$(".selector").validate({showErrors: function(errorMap, errorList) {$("#summary").html("Your form contains " + this.numberOfInvalids()+ " errors, see details below.");this.defaultShowErrors();}})<script type="text/javascript"></script>// 手機號碼驗證jQuery.validator.addMethod("mobile", function(value, element) {var length = value.length;var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+/d{8})$/return this.optional(element) || (length == 11 && mobile.test(value));}, "手機號碼格式錯誤"); // 電話號碼驗證 jQuery.validator.addMethod("phone", function(value, element) {var tel = /^(0[0-9]{2,3}/-)?([2-9][0-9]{6,7})+(/-[0-9]{1,4})?$/;return this.optional(element) || (tel.test(value));}, "電話號碼格式錯誤");// 郵政編碼驗證 jQuery.validator.addMethod("zipCode", function(value, element) {var tel = /^[0-9]{6}$/;return this.optional(element) || (tel.test(value));}, "郵政編碼格式錯誤");// QQ號碼驗證 jQuery.validator.addMethod("qq", function(value, element) {var tel = /^[1-9]/d{4,9}$/;return this.optional(element) || (tel.test(value));}, "qq號碼格式錯誤");// IP地址驗證jQuery.validator.addMethod("ip", function(value, element) {var ip = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;return this.optional(element) || (ip.test(value) && (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256));}, "Ip地址格式錯誤");// 字母和數字的驗證jQuery.validator.addMethod("chrnum", function(value, element) {var chrnum = /^([a-zA-Z0-9]+)$/;return this.optional(element) || (chrnum.test(value));}, "只能輸入數字和字母(字符A-Z, a-z, 0-9)");// 中文的驗證jQuery.validator.addMethod("chinese", function(value, element) {var chinese = /^[/u4e00-/u9fa5]+$/;return this.optional(element) || (chinese.test(value));}, "只能輸入中文");// 下拉框驗證$.validator.addMethod("selectNone", function(value, element) {return value == "請選擇";}, "必須選擇一項");// 字節長度驗證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個字節)"));
新聞熱點
疑難解答