使用jQuery Validation插件的自定义方法

时间:2013-03-23 16:29:43

标签: jquery jquery-validate

我试图在Jquery中使用自定义验证。所有编码部分都是正确的,但我没有得到它出错的地方......这是代码的一部分。

Password:<input type="password" id="pnameTxt" name="pnameTxt" placeholder="Enter Password" size=12 class='required'><br>
Confirm Password:<input type="password" id="pnameTxt2" name="pnameTxt2" placeholder="Retype Password" size=15 class='required passwordCheck'><br>

自定义验证方法:

 $.validator.addMethod("passwordCheck",function (value,element){
          return value==$("#pnameTxt").val(); 

        }, 'Password and Confirm Password should be same');

2 个答案:

答案 0 :(得分:34)

您的代码正常运行。使用.validate()初始化插件时,还必须将规则分配给字段。

工作演示:http://jsfiddle.net/KrLkF/

$(document).ready(function () {

    $.validator.addMethod("passwordCheck", function (value, element) {
        return value == $("#pnameTxt").val();
    }, 'Password and Confirm Password should be same');

    $('#myform').validate({ // initialize the plugin
        rules: {
            pnameTxt2: {
                passwordCheck: true
            }
        }
    });

});

HOWEVER ,您无需为此功能编写自定义方法。 jQuery Validate插件已经有equalTo rule,以下是如何使用它。

工作演示:http://jsfiddle.net/tdhHt/

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            pnameTxt2: {
                equalTo: "#pnameTxt" // using `id` of the other field
            }
        },
        messages: {
            pnameTxt2: {
                equalTo: "Password and Confirm Password should be same"
            }
        }
    });

});

答案 1 :(得分:1)

您是否正确初始化了验证插件? 当我将html放在form然后initialize the plugin时,它会按预期工作。

<form id="test">
Password:<input type="password" id="pnameTxt" name="pnameTxt" placeholder="Enter Password" size=12 class='required'><br>
Confirm Password:<input type="password" id="pnameTxt2" name="pnameTxt2" placeholder="Retype Password" size=15 class='required passwordCheck'><br>
<input type="submit">
</form>
$.validator.addMethod("passwordCheck",function (value,element){
      return value==$("#pnameTxt").val(); 

    }, 'Password and Confirm Password should be same');

$('#test').validate();
相关问题