本文實例講述了jQuery validate外掛程式實作ajax驗證重複的2種方法。分享給大家參考,具體如下:
jquery validate 經過這種多年的改良,已經很完善了。它能滿足80%的驗證需要,如果validate自帶的功能,不能滿足我們需求,它提供了addMethod來擴充功能。下面就舉個小例子來說明addMethod的用法。
完整demo實例程式碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <title>jquery validate ajax check exist</title> <head> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script> <script> $(document).ready(function(){ jQuery.validator.addMethod("phonecheck", function(value, element) { string = value.match(/0(\d{2,2})-(\d{7,7})/ig); if(string != null){ return true; }else{ return false; } }, "telphone number like 021-1234567"); jQuery.validator.addMethod("phonesame", function(value, element) { var flag = 1; $.ajax({ type:"POST", url:'tel.php', async:false, data:{'tel':value}, success: function(msg){ if(msg == 'yes'){ flag = 0; } } }); if(flag == 0){ return false; }else{ return true; } }, "sorry number have been exist"); $("#myform").validate({ errorPlacement: function(error, element) { error.insertAfter(element); }, rules:{ username:{ required:true, remote:{ url:"tel.php", type:"post", dataType:"html", data:{ username:function(){return $("#username").val();} }, dataFilter: function(data, type) { if (data == "yes") return true; else return false; } } }, telphone:{ required:true, rangelength:[11,11], phonecheck:true, phonesame:true } }, messages:{ telphone:{ required:"Please enter your phone", rangelength:"phone must be 11 numbers" }, username:{ required:"Please enter your username", remote:"the username have been exist" } }, debug:true }) }); </script> </head> <body style="margin-left:500px;margin-top:100px;"> <div style="font-size:24px;">021-1234567 or tank exist</div><br> <form id="myform" method="post"> <label>Your telphone</label> <input name="telphone" class="required" value="" /><br><br> <label>Your username</label> <input name="username" id="username" class="required" value="" /> <br/> <input type="submit" value="Submit"/> </form> </body> </html>
在這裡推薦大家使用jquery validate,用熟了,很方便。
更多關於jQuery外掛相關內容有興趣的讀者可查看本站專題:《jQuery常用外掛及用法總結》
希望本文所述對大家jQuery程式設計有所幫助。