jQuery 如果其他字段不为空,则验证调用自定义方法

jQuery validate call custom method if other field not empty

我正在使用 jQuery 验证插件,并且我有一个自定义方法,其中我正在验证的字段必须大于另一个字段。

我遇到的问题是当另一个字段为空(不需要)时,我收到一条验证消息,指出该值必须大于没有值的其他字段。

仅当其他字段有值或至少通过该部分的验证时,我才需要调用我的自定义方法。

$.validator.addMethod("greaterThan", function (value, element, param) {
    var $otherElement = $(param);
    return parseInt(value, 10) > parseInt($otherElement.val(), 10);
});



rules: {
    other_field: {
        required: false,
        min: 0,
        number: true
    },
    my_field: {
        required: true,
        min: 1,
        number: true,
        greaterThan: "#other_field"
    }
}

I need to call my custom method only if the other field has a value

因此,在执行规则之前,只需使用条件来查看它是否为空...

$.validator.addMethod("greaterThan", function (value, element, param) {
    var $otherElement = $(param);
    if ($otherElement != '') { // <- the other field not empty?
        return parseInt(value, 10) > parseInt($otherElement.val(), 10);
    };
    return true; // <- other field was empty, no error message
});

根据需要调整逻辑...可能 trim 空格、测试零等