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="https://www.jb51.net/jquery.min.js"></script> <script type="text/javascript" src="https://www.jb51.net/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> <div>021-1234567 or tank exist</div><br> <form method="post"> <label>Your telphone</label> <input value="" /><br><br> <label>Your username</label> <input value="" /> <br/> <input type="submit" value="Submit"/> </form> </body> </html>

在这里推荐大家使用jquery validate,用熟了,很方便。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwgxg.html