根据问题返回不同的消息

时间:2014-01-31 12:07:44

标签: javascript jquery jquery-validate

我有一个jQuery Validation addMethod,用于检查密码长度并确保该值与另一个密码字段值匹配。

我看不出如何根据原因让addMethod返回自定义消息,是否可能?

两个密码字段是:

<input type="password" class="required" name="Password" id="Password">
<input type="password" class="required" name="ConfirmPassword" id="ConfirmPassword">

代码:

$.validator.addMethod("arePasswordsValid", function(value, element) {

    this.isValid = true;
    this.errorMessage = "";
    this.options = {
         minLength: 6,
         maxLength: 20
    };

    if (value != $('#ConfirmPassword').val()) {
        this.errorMessage = "Password and Confirm Password should be same";
        this.isValid = false;
    }
    if (value.length < this.options.minLength || value.length > this.options.maxLength) {
        this.errorMessage = "The password must be between 6 and 20 characters long";
        this.isValid = false;
    }
    return this.isValid;
}, this.errorMessage);

$('form').find('input#Password').rules("add", {
     required: true,
     arePasswordsValid: true
});

由于this.errorMessage无法访问,上述内容无效,只要需要填写必填字段,表单才会生效。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

1)您的minlengthmaxlength规则拼写错误。请注意,大写L不正确。

2)minlengthmaxlength规则可以简单地合并到the rangelength rule

rangelength: [6,20]

3)你正在使它变得无比复杂。只需使用the equalTo rule即可。你的是它旨在解决的确切场景。

4)使用messages选项更改任何消息的确切措辞。

工作演示:http://jsfiddle.net/7pN8A/2/

$('#myform').validate({
    rules: {
        Password: {
            required: true,
            rangelength: [6,20]
        },
        ConfirmPassword: {
            equalTo: "#Password"  // this is all you need... the rules for the other will apply
        }
    },
    messages: {  // optional, over-ride default messages
        Password: {
            rangelength: "The password must be between {0} and {1} characters long"
        },
        ConfirmPassword: {
            equalTo: "Password and Confirm Password should be same"
        }
    }
});

您的HTML:

<form id="myform">     
    <input type="password" class="required" name="Password" id="Password">
    <input type="password" class="required" name="ConfirmPassword" id="ConfirmPassword">
</form>

答案 1 :(得分:-1)

尝试制定更通用的方法。而不是直接输出消息。您可以先保存所有信息,然后拆分验证和发送消息。这样,即使是复杂的情况也不应成为问题。