在 jQuery Validate 插件中使用 addMethod

问题描述 投票:0回答:3

我想使用 jQuery Validate 插件的自定义验证方法 (addMethod) 验证文本框,但我的代码不起作用。 谁能帮我找出错误吗? 我以前从未使用过自定义验证方法,所以我很难找到这段代码中出错的地方。

这是我的代码:

$(document).ready(function () {

jQuery.validator.setDefaults({
  // where to display the error relative to the element
  errorPlacement: function(error, element) {
      error.appendTo(element.parent().find('div.myErrors'));
     }
 });

 jQuery.validator.addMethod(
"selectnic"
function(value,element){
if(element.value == /^[0-9]{9}[vVxX]$/)
   return false;
   else return true;
},
"wrong nic number"
); 



    $('#basicDetails').validate({ // initialize the Plugin
        rules: {
                fname: {
                    required: true,
                    lettersonly: true,
                },
                lname: {
                    required: true,
                    lettersonly: true,
                },  
            },
        messages: {
           fname: {
                required:"Please enter your first name",
                lettersonly: "Login format not valid",

            },
             lname: {
                required:"Please enter your last name",
                lettersonly: "Login format not valid",  
            },
        },
        submitHandler: function (form) { 
            alert('valid form submitted'); 
            return false; 
        }
    });

});

..html代码....

<form action="#" method="post"  id="basicDetails" runat="server">

 <table width="68%" border="0" cellpadding="6" cellspacing="6">


 <tr>
                                    <td>&nbsp;</td>
                                    <td> First name </td>
                                    <td>:</td>
                                    <td><input type="text" name="fname" id="fname" class="textbox" placeholder="Required field"/><div class="myErrors"></div></td> &nbsp;
                                    <td align="right"> Last name&nbsp; :</td>
                                    <td><input type="text" name="lname" class="textbox" id="lname" placeholder="Required field"/><div class="myErrors"></div></td>
                                </tr>

                                <tr>
                                    <td>&nbsp;</td>
                                    <td width="147" > NIC no </td>
                                    <td> : </td>
                                    <td width="172"><input type="text" name="nic" id="nic"   class="textbox"  placeholder="Required field"/><div class="myErrors"></div></td>
                                    <td width="167" align="right">Passport no &nbsp; :</td>
                                    <td width="167" id="showPP"> <input type="text" name="passport" class="textbox" id="ppnu" placeholder="Required field"/></td>    
                                </tr>
                                <tr>
                                    <td>&nbsp;</td>
                                    <td>&nbsp;</td>
                                    <td colspan="3"><input type="submit" name="submit"  value="Submit "class="submit"   id="submit" />&nbsp; &nbsp;
                                    <input type="submit" name="reset"  value="Reset "class="reset" />
                                    </td>                                
                                </tr>


 </table>





</form>

......编辑我的代码后......

$(document).ready(function () {



jQuery.validator.setDefaults({
  // where to display the error relative to the element
  errorPlacement: function(error, element) {
      error.appendTo(element.parent().find('div.myErrors'));
     }
 });

 jQuery.validator.addMethod("selectnic", function(value, element){
    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return false;
    } else {
        return true;
    };
}, "wrong nic number"); 


    $('#basicDetails').validate({ // initialize the Plugin


        rules: {
                fname: {
                    required: true,
                    lettersonly: true,
                        },
                lname: {
                    required: true,
                    lettersonly: true,
                    },

                 nicnumber: {
                            // other rules,
                        selectnic: true // <-  declare the rule someplace!
                            }


            },


        messages: {

           fname: {
                required:"Please enter your first name",
                lettersonly: "Login format not valid",

            },
             lname: {
                required:"Please enter your last name",
                lettersonly: "Login format not valid",

            },
        },


        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });

});
jquery jquery-validate
3个回答
52
投票

下面的进展编辑概述了三个不同的问题。


1) 您在

selectnic
function(
之间漏掉了一个逗号。

此外,在使用

regex
...

时请尝试使用此格式
jQuery.validator.addMethod("selectnic", function(value, element){
    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return false;  // FAIL validation when REGEX matches
    } else {
        return true;   // PASS validation otherwise
    };
}, "wrong nic number"); 

编辑:这个答案假设你原来的

regex
和逻辑都是正确的。 当
false
匹配时,您的逻辑将返回
regex
false
表示验证失败,您将看到错误消息。


2)编辑2:

创建新方法后,您还必须使用它们。 我没有看到您的代码中任何地方使用了

selectnic
规则/方法。

示例

rules: {
    myFieldName: {
        // other rules,
        selectnic: true // <-  declare the rule someplace!
    }
}

3)编辑3:

最后,OP 最初的

true/false
逻辑是倒退的。 他想通过正则表达式匹配的验证……因此,需要
return true

    if (/^[0-9]{9}[vVxX]$/.test(value)) {
        return true;   // PASS validation when REGEX matches
    } else {
        return false;  // FAIL validation
    };

演示:http://jsfiddle.net/DzvNr/


1
投票

这是我的解决方案,包括希腊字符。

$.validator.addMethod('alphabet', function (value, element) {

        let regExName = /^[A-Za-zΑ-Ωα-ωίϊΐόάέύϋΰήώ]+$/;
        return (regExName.test(value));

    }, 'There are non alphabetic characters!');
  $("#orderForm").validate({
     rules: {
          first_name: {
             required: true,
             alphabet: true
          }
});

0
投票
    jQuery.validator.addMethod("weekText",function(a,b){
        
        //return a=a.replace(/\s+/g,""),this.optional(b)||a.length>9&&a.match(/^(\+?61-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/)
        //return a=a.replace(/\s+/g,""),this.optional(b)||a.match(/^(\+?61-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/);
        let result = a.match(/^(\+?61-?)/);
        let result1 = a.match(/^(\+?4-?)/);
        if(result == "+61,+61")
        {
            return true;
            //alert("dsdsfsf");
            //return a=a.match(/^(\+?61-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/);
        }
        else if(result == "+4,+4")
        {
            return true;
            //alert("Here1");
            //return a=a.match(/^(\+?04-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/);
        }
        else
        {
            return false;
        }
        
    },"Please specify a valid phone number");
var wh = jQuery("#footerform").validate({
    rules: {
    'fullname':{
    required:true
    },
    
    'footer-email':{
    required: true,
    email:true
    },
    'footer-phone':{
    required:true,
    //phoneAu: true,
    //rangelength : [5, 16],
    weekText: true
    },
    'footer-address':{
    required:true,
    lettersonly: true
    },
    'footer-message':{
    lettersonly: true
    }
  },
  messages: {
    'fullname': {
    required: "Please enter your name."
    },
    
    'footer-email': {
    required: "Please enter your email.",
    email: "Please enter valid email address."
    },
    'footer-phone' : {
    required: "Please enter your phone.",
    //rangelength : "Please enter valid phone number.",
     weekText : "Please specify a valid phone number"
    },
    'footer-address': {
    required: "Please enter your address.",
    lettersonly: "Please enter Letter Only.",
    },
    'footer-message':{
    lettersonly: "Please enter Letter Only.",
    }
  },
  errorPlacement: function(error, element)
  {
  error.insertAfter( element );
  },
  errorElement: "label",
  errorClass: "error"
});
jQuery('#footerform .submit_btn_box').on('click', function(event) {
if (wh.form())
{
/*var response = jQuery('#g-recaptcha-response').val();
  if(response.length == 0  )
  {
    jQuery('#contactform .recaptcha-error-message').show();
    return false;
  }
  else
  {
    jQuery('#contactform .recaptcha-error-message').hide();
  } */          
}
else
{
  /*var response = jQuery('#g-recaptcha-response').val();
  if(response.length==0  )
  {
  jQuery('#contactform .recaptcha-error-message').show();
  return false;
  }
  else
  {
  jQuery('#contactform .recaptcha-error-message').hide();
  }*/
  event.preventDefault();
  event.stopPropagation();
}
© www.soinside.com 2019 - 2024. All rights reserved.