密码强度验证

时间:2017-06-14 10:02:48

标签: jquery jquery-validate

我使用jquery验证来检查密码强度,但它无法正常工作。确认密码匹配部分正在运行,但不是自定义规则。我在这里想念的是什么?

脚本:

 $(document).ready(function () {
        $.validator.addMethod("pwcheck", function(value) {
            return /^[A-Za-z0-9\d=!\-@._*]*$/.test(value) // consists of only these
                &&
                /[A-Z]/.test(value) // has a uppercase letter
                &&
                /\d/.test(value); // has a digit
        }, "Please ensure your password contains an uppercase letter, number and symbol and is between 8 & 15 characters.");


$('#changePassword').validate({
    rules: {
        ConfirmPassword: {
            equalTo: "#password"
        },
        pwRules: {
            pwcheck :true
        }
    },
    messages: {
        ConfirmPassword: "Passwords do not match"
    }
});

HTML:

 <label class="typ2">Old Password:</label>
        @Html.Password("Password", null, new { @class = "typ2 shad1 trans1", maxlength = "50", required = "required" })
        <br class="floatClear" />

        <label class="typ2">Login Password:</label>
        @Html.Password("NewPassword", null, new { @class = "typ2 shad1 trans1",  maxlength = "50", id = "password", required = "required" })
        <span style="position: absolute;margin-top: 0;margin-left: 10px;">Please ensure your password contains an uppercase letter, number and symbol.<br /> Passwords must be between 8 &amp; 15 characters.</span>
        <label style="color:red !important; margin-left: 10px; font-size:24px;">*</label>
        <br class="floatClear" />

        <label class="typ2">Confirm Password:</label>
        @Html.Password("ConfirmPassword", null, new { @class = "typ2 shad1 trans1", minlength = "8", maxlength = "50", id = "confirm", required = "required" })
        <br class="floatClear" />

1 个答案:

答案 0 :(得分:1)

引用OP的comment

  

我终于找到了问题所在。我需要将'pwcheck'添加到输入的类名。类似问题的其他答案都没有显示出这一关键步骤。 :(

pwcheck放在字段的类中并不是“关键步骤”;它只是一种分配规则的不同方式。有几种方法可以使用此插件分配规则。

您的根本问题如下。通过rules对象分配规则时,必须使用相应字段的name。由于pwRules不是字段的name,因此会忽略此规则分配。

$('#changePassword').validate({
    rules: {
        ConfirmPassword: {        // <- field NAME
            equalTo: "#password"  // <- rule
        },
        pwRules: {    // <- this is not the NAME of a field
            pwcheck :true
        }
    ....

应该是......

    rules: {
        ConfirmPassword: {        // <- field NAME
            equalTo: "#password"  // <- rule
        },
        Password: {               // <- field NAME
            pwcheck :true         // <- rule
        } ....