Jquery Validate:在另一个方法中调用validate方法

时间:2013-06-27 10:59:20

标签: jquery jquery-validate unobtrusive-validation

在自定义验证方法中,我想调用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;
},

有没有办法调用验证方法并提供所需的参数?

1 个答案:

答案 0 :(得分:0)

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

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