«

jQuery validate插件实现ajax验证重复的2种方法

时间:2024-3-2 10:02     作者:韩俊     分类: Javascript


本文实例讲述了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程序设计有所帮助。

标签: javascript

热门推荐