How can I validate that the max field is greater than the min field?

后端 未结 2 1559
耶瑟儿~
耶瑟儿~ 2021-01-02 05:26

I have a few sets of min and max fields in a form, where the user can specify a range by filling in a min and a max. I\'m using jQuery\'s Validate plugin for my form validat

2条回答
  •  孤街浪徒
    2021-01-02 05:44

    Ok, here's something that should work. The rule is based on the built in equalTo method:

    $.validator.addMethod("greaterThan", function (value, element, param) {
        var $min = $(param);
    
        if (this.settings.onfocusout) {
            $min.off(".validate-greaterThan").on("blur.validate-greaterThan", function () {
                $(element).valid();
            });
        }
    
        return parseInt(value) > parseInt($min.val());
    }, "Max must be greater than min");
    

    Example: http://jsfiddle.net/tUPQc/2/


    To make the rule a bit more generic, you'll have to need to use addClassRules:

    $.validator.addMethod("greaterThan", function (value, element, param) {
        var $element = $(element)
            , $min;
    
        if (typeof(param) === "string") {
            $min = $(param);
        } else {
            $min = $("#" + $element.data("min"));
        }
    
        if (this.settings.onfocusout) {
            $min.off(".validate-greaterThan").on("blur.validate-greaterThan", function () {
                $element.valid();
            });
        }
        return parseInt(value) > parseInt($min.val());
    }, "Max must be greater than min");
    
    $.validator.addClassRules({
        greaterThan: {
            greaterThan: true
        }
    });
    

    Then in your HTML:

    
    

    Example: http://jsfiddle.net/tUPQc/3/

提交回复
热议问题