jquery.validate使用詳解
一、簡單應(yīng)用實例:
1.用class樣式進行驗證,用法簡單,但不能自定義錯誤信息,只能修改jquery-1.4.1.min.js中的內(nèi)置消息,也不支持高級驗證規(guī)則。
<script type="text/javascript" language="javascript" src="http://chabaoo.cn/Scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript" language="javascript" src="http://chabaoo.cn/Scripts/jquery.validate.min.js"></script> <h2>ValidateTest</h2> <form id="loginForm" action="post"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <input type="text" id="UserEmail" class="required email" /></td> </tr> <tr> <td> <input type="password" id="Password" class="required" /></td> </tr> <tr> <td> <input type="submit" value="submit" onclick="checkInput();" /> </td> </tr> </table> </form> <script language="javascript" type="text/javascript"> function checkInput() { if ($("#loginForm").valid()) { return true; } return false; } </script>
當(dāng)然,如果不希望使用onclick事件進行提交驗證,也可以在頁面加載時加上jQuery的監(jiān)控,代碼如下:
$(document).ready(function () { jQuery("#loginForm").validate(); });
這時就不需要在提交按鈕上加 onclick="checkInput();"這個事件了。
2.使用Json字符串驗證,使用該規(guī)則驗證,必須額外引入jquery.metadata.pack.js文件
修改上面的兩個INPUT如下:
<input type="text" id="UserEmail" class="{validate:{ required:true,email:true }}" /> <input type="password" id="Password" class="{validate:{required:true,minlength:6,messages:{required:'請輸入密碼 ',minlength:'密碼至少6位'}}}" />
可以看到,我們已經(jīng)可以自定義錯誤消息了。
另外必須在頁面中加上以下代碼:
$(document).ready(function () { $("#loginForm").validate({ meta: "validate" }); });
二、驗證規(guī)則的應(yīng)用
1.使用class驗證的規(guī)則:
在class中可以使用:required,email,number,url,date,dateISO,dateDE,digits,creditcard,phoneUS
可以增加屬性:minlength,maxlength,min,max,accept,remote(注:請檢查是否返回是bool還是xml),equalTo='#password'
沒有找到使用辦法的內(nèi)置方法:required(dependency-expression),required(dependency-callback),range,rangelength
2.使用Json對象驗證的規(guī)則:
在class中進行如下定義:class=“{validate:{required:true,minlength:6,messages:{required:'請輸入密碼',minlength:'密碼太短啦至少6位'}}}”
我們?nèi)钥蛇M行以下定義:number:true, email:true, url:true, date:true, dateISO:true, dateDE:true, digits:true, creditcard:true, phoneUS:true
min:3, max:10, minlength:3, maxlength:10,required: '#other:checked'【此處表達式函數(shù)為required(dependency-expression)】
相比使用class來說,我們已經(jīng)可以使用range方法了,可定義為數(shù)字range:[3,10],字符串長度rangelength:[3,10],remote:url,accept:'.csv|.jpg|.doc|.docx', equalTo:'#Password'
沒有找到使用方法的內(nèi)置方法:required(dependency-callback)
三、高級驗證方法
在前面說到的簡單驗證中,使用起來非常簡單,有些傻瓜式的味道,但畢竟有些內(nèi)置規(guī)則不能使用。但要想做到靈活運用,還是需要通過JS編碼來完成。這樣不但所有的內(nèi)置規(guī)則可以使用,而且我們還可以自定義驗證規(guī)則。以下實例我從易到難逐個列出:
1.編寫JS的簡單方法
仍以登錄驗證為例:
<script type="text/javascript" language="javascript" src="http://chabaoo.cn/Scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript" language="javascript" src="http://chabaoo.cn/Scripts/jquery.validate.min.js"></script> <h2>Validate-High</h2> <form action="" id="loginForm" method="post"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <input type="text" id="UserEmail" /> </td> </tr> <tr> <td> <input type="password" id="Password" /> </td> </tr> <tr> <td> <input type="submit" value="submit"/> </td> </tr> </table> </form> <script language="javascript" type="text/javascript"> $(document).ready(function () { var validateOpts = { rules: { UserEmail: { required: true, email: true }, Password: { required: true } }, messages: { UserEmail: { required: "請輸入郵箱地址", email: "郵箱地址不正確" }, Password: { required: "請輸入密碼" } } }; $("#loginForm").validate(validateOpts); }); </script>
我們只需設(shè)置validate的參數(shù)即可。
2.equalTo的使用,一般在注冊時會用到
<script type="text/javascript" language="javascript" src="http://chabaoo.cn/Scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript" language="javascript" src="http://chabaoo.cn/Scripts/jquery.validate.min.js"></script> <h2>ValidateHigh</h2> <form action="" id="loginForm" method="post"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <input type="text" id="UserEmail" /> </td> </tr> <tr> <td> <input type="password" id="Password" /> </td> </tr> <tr> <td> <input type="password" id="RePassword" /> </td> </tr> <tr> <td> <input type="submit" value="submit"/> </td> </tr> </table> </form> <script language="javascript" type="text/javascript"> $(document).ready(function () { var validateOpts = { rules: { UserEmail: { required: true, email: true }, Password: { required: true }, RePassword: { equalTo: "#Password" } }, messages: { UserEmail: { required: "請輸入郵箱地址", email: "郵箱地址不正確" }, Password: { required: "請輸入密碼" }, RePassword: { equalTo: "兩次輸入密碼必須相同" } } }; $("#loginForm").validate(validateOpts); }); </script>
3.required(dependency-callback)的使用,綠色字體。
var validateOpts = { rules: { age: { required: true, min: 3 }, parent: { required: function (element) { return $("#age").val() < 13; } } } }
4.自定義規(guī)則,使用addMethod方法,如下:
//方法接收三個參數(shù)(value,element,param)
//value是元素的值,element是元素本身 param是參數(shù),我們可以用addMethod來添加除built-in Validation methods之外的驗證方法
//比如有一個字段,只能輸一個字母,范圍是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");
這樣我們就可以在rules中加上這個規(guī)則,如下
var validateOpts = { rules: { selectorId: { af: ["a","f"]//如果只有一個參數(shù),直接寫,如果af:"a",那么a就是這個唯一的參數(shù),如果多個參數(shù),用在[]里,用逗號分開 } } }
另外,經(jīng)過試驗,在Json方式中,我們可以使用af:['a','f'],這個驗證可以起作用,在class方式中,在某個元素上增加af='af',驗證也可以起到作用。
5.ajax驗證,使用remote
remote: { url:"CheckEmail", type:"post", dataType:"json" }
如果我們驗證的方法是返回Boolean類型,這個方法是沒有問題的。但很多時候我們可能返回的信息會更多,或者返回其它類型,這時我們可以重新定義一個新的remote方法,示例如下(返回一個Json對象):
$.validator.addMethod("jsonremome", function (value, element, param) { if (this.optional(element)) return"dependency-mismatch"; var previous =this.previousValue(element); if (!this.settings.messages[element.name]) this.settings.messages[element.name] = {}; previous.originalMessage =this.settings.messages[element.name].remote; this.settings.messages[element.name].remote = previous.message; param =typeof param =="string"&& { url: param} || param; if (previous.old !== value) { previous.old = value; var validator =this; this.startRequest(element); var data = {}; data[element.name] = value; $.ajax($.extend(true, { url: param, mode: "abort", port: "validate"+ element.name, dataType: "json", data: data, success: function (response) { validator.settings.messages[element.name].remote = previous.originalMessage; //var valid = response === true; var valid = response.Result ===true; if (valid) { var submitted = validator.formSubmitted; validator.prepareElement(element); validator.formSubmitted = submitted; validator.successList.push(element); validator.showErrors(); } else { var errors = {}; //var message = (response.Message || validator.defaultMessage(element, "jsonremote")); var message = response.Message ||"遠程驗證未通過"; errors[element.name] = $.isFunction(message) ? message(value) : message; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); } }, param)); return"pending"; } elseif (this.pending[element.name]) { return"pending"; } return previous.valid; });
服務(wù)器端方法如下(MVC中):
public JsonResult CheckEmail(string UserEmail) { returnnew JsonResult { Data =new { Result =false, Message="Please change the filed" } }; }
我們就可以使用jsonremote來取代remote方法了。當(dāng)然,remote方法依然可以使用。
6.錯誤顯示規(guī)則
var validateOpts = { wrapper: "div",// default has no wrapper errorClass: "invalid", // the default value is error errorElement: "em", // default value is lable errorLabelContainer: "#messageBox", // to gather all the error messages }
以上就是本文的全部內(nèi)容,希望能給大家一個參考,也希望大家多多支持腳本之家。
- jquery.validate 自定義驗證方法及validate相關(guān)參數(shù)
- jQuery.Validate驗證庫的使用介紹
- 基于Bootstrap+jQuery.validate實現(xiàn)Form表單驗證
- jquery.validate提示錯誤信息位置方法
- jquery.validate使用時遇到的問題
- jQuery.validate 常用方法及需要注意的問題
- jquery.validate的使用說明介紹
- 利用jQuery.Validate異步驗證用戶名是否存在(推薦)
- 功能強大的jquery.validate表單驗證插件
- jquery.validate自定義驗證用法實例分析【成功提示與擇要提示】
相關(guān)文章
jQuery實現(xiàn)簡單的網(wǎng)頁換膚效果示例
這篇文章主要介紹了jQuery實現(xiàn)簡單的網(wǎng)頁換膚效果,涉及jQuery事件響應(yīng)及頁面元素屬性動態(tài)變換操作技巧,需要的朋友可以參考下2016-09-09jquery中的ajax方法怎樣通過JSONP進行遠程調(diào)用
這篇文章主要介紹了jquery中的ajax方法怎樣通過JSONP進行遠程調(diào)用,需要的朋友可以參考下2014-05-05jquery異步循環(huán)獲取功能實現(xiàn)代碼
頁面html的repeater控件中有一個span,需要根據(jù)指定ID異步獲取相關(guān)信息。2010-09-09Zero Clipboard實現(xiàn)瀏覽器復(fù)制到剪貼板的方法(多個復(fù)制按鈕)
這篇文章主要介紹了Zero Clipboard實現(xiàn)瀏覽器復(fù)制到剪貼板的方法,帶有多個復(fù)制按鈕效果,涉及jQuery插件ZeroClipboard.js具體使用步驟與相關(guān)技巧,需要的朋友可以參考下2016-03-03