Home > Article > Web Front-end > 2 ways to implement ajax validation duplication using the jQuery validate plug-in_jquery
The examples in this article describe two methods for the jQuery validate plug-in to implement ajax verification duplication. Share it with everyone for your reference, the details are as follows:
jquery validate has been perfected after many years of improvement. It can meet 80% of verification needs. If the built-in function of validate cannot meet our needs, it provides addMethod to extend the function. Let's give a small example to illustrate the usage of addMethod.
The complete demo example code is as follows:
<!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>
I recommend you to use jquery validate here. Once you are familiar with it, it is very convenient.
Readers who are interested in more content related to jQuery plug-ins can check out the special topic of this site: "Summary of common jQuery plug-ins and usage"
I hope this article will be helpful to everyone in jQuery programming.