4

在自定义验证方法中,我想调用 minLength 验证方法。

我试过这个:

$.validator.addMethod("myMethod", function (value, element, params) {
    var minLengthResult = $.validator.methods.minlength.call(this, value, element);
    if(minLengthResult === false) {
        return true;
    }

    // check the value
});

但是,如果我调试 minlength 验证方法,param 对象未定义,并且该函数始终返回 false。

// http://docs.jquery.com/Plugins/Validation/Methods/minlength
minlength: function( value, element, param ) {
    // param is undefined if i call this function using
    // $.validator.methods.minlength.call()

    var length = $.isArray(value) ? value.length : this.getLength($.trim(value), element);
    return this.optional(element) || length >= param;
},

有什么方法可以调用验证方法并提供所需的参数吗?

4

1 回答 1

0

也许不完全是您正在寻找的东西,但我总是使用自定义代码段来验证表单。在本例中,无效字段的标题属性设置为错误消息,因此您可以显示 jQuery 提示,例如:

var validation = {
    name: [/.+/i, 2, 90, "Invalid naam", true, "Name"],
    email: [/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i, 0, 150, "Invalid email",        true, "Email"]
}

调用验证:

$("#form").submit(function(e) {
    e.preventDefault();     

    //validation
    var error = false;
    $(this).find("input").each(function() {
        var field = $(this).attr("name");
        var val = $(this).val();

        if(validation[field]) {
            $(this).removeClass("error"); //clear previous errors

        //invalid
            if(!val.match(validation[field][0]) && val)
                error = [field, validation[field][3]];

            //too short
            if(val.length < validation[field][1] && val)
                error = [field, validation[field][5] + " requires at least " + validation[field][1] + " characters"];

            //too long
            if(val.length > validation[field][2] && val)
                error = [field, validation[field][5] + " has a maximum of " + validation[field][2] + " characters"];

            //missing
            if(!val && validation[field][4])
                error = [field, validation[field][5] + " is required"];
        }

        if(error)
            return false;
    });

    //errors?
    if(error) {
        $(this).find("input[name=" + error[0] + "]").addClass("error").focus().attr("title", error[1]);
        return false;
    }

    //submit form! Everything is valid
});
于 2013-06-27T11:34:52.687 回答