在 jQuery Validate 插件中使用 addMethod

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23658228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:20:36  来源:igfitidea点击:

Use addMethod in jQuery Validate plugin

jqueryjquery-validate

提问by Erandi

I want to validate a text box using jQuery Validate plugin's custom validation method (addMethod) but my code doesn't work. Can anyone help me to find the error? I have never used custom validation method before so it's bit hard for me to find where I went wrong in this code.

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

This is my code:

这是我的代码:

$(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 code ....

..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>

.....after editing my code ....

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

$(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
        }
    });

});

回答by Sparky

There are three different issues as outlined by the progressing edits below.

以下正在进行的编辑概述了三个不同的问题。



1) You missed a comma just between selectnicand the function(.

1) 您在selectnic和之间错过了一个逗号function(

Also, try this format instead when using regex...

另外,请在使用时尝试这种格式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"); 

EDIT: This answer assumes your original regexand logic are both correct. Your logic returns falsewhen the regexis a match. falsemeans that validation failed and you will see the error message.

编辑:此答案假定您的原始regex逻辑和逻辑都是正确的。您的逻辑falseregex匹配时返回。 false表示验证失败,您将看到错误消息。



2) EDIT 2:

2)编辑2:

After creating new methods, you also have to usethem. I do not see the selectnicrule/method used anyplace in your code.

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

Example:

示例

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


3) EDIT 3:

3)编辑3:

And finally, the OP's original true/falselogic was backwards. He wanted to PASS validation upon a regex match… therefore, needs to return true.

最后,OP 的原始true/false逻辑是倒退的。他想在正则表达式匹配时通过验证……因此,需要return true.

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

DEMO: http://jsfiddle.net/DzvNr/

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