jQuery 如何验证最大字段大于最小字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14347177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:29:05  来源:igfitidea点击:

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

jqueryjquery-validate

提问by froadie

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 validation. I'd like to set up a validation rule that enforces that the max field is greater than the min. This would be invoked whenever the max orthe min fields values are changed.

我在表单中有几组最小值和最大值字段,用户可以在其中填写最小值和最大值来指定范围。我正在使用 jQuery 的 Validate 插件进行表单验证。我想设置一个验证规则,强制最大值字段大于最小值。每当更改最大最小字段值时都会调用此方法。

I know I can set up some sort of basic custom validation method like this:

我知道我可以设置某种基本的自定义验证方法,如下所示:

$.validator.addMethod("greaterThan",
    function(value, max, min){
        return parseInt(value) > parseInt($(min).val());
    }, "Max must be greater than min"
);

And then add a rule for the max element:

然后为 max 元素添加规则:

rules: {
    maxTruck: {greaterThan: '#minTruck'}
}

But it's a bit more complicated because this only applies when the max field is changed, not the min. Is there any simple way to do this without having to write a lessThan method and apply that to the min field?

但这有点复杂,因为这仅适用于更改 max 字段而不是 min 字段的情况。有没有什么简单的方法可以做到这一点,而不必编写 lessThan 方法并将其应用于 min 字段?

And then another thing I'd like to tackle - is there any simple way that I can apply this generically instead of having to enumerate each max field and which min it maps to? So that I can just have a min and max class and call something like:

然后我想解决的另一件事 - 有没有什么简单的方法可以通用地应用它,而不必枚举每个最大字段以及它映射到哪个最小值?这样我就可以有一个最小和最大类并调用类似的东西:

$(".max").rules('add', { greaterThan: ".min" });

And somehow set up the method to be able to figure out (maybe based on a shared attribute?) which min the max field is paired with?

并以某种方式设置方法以便能够找出(可能基于共享属性?) max 字段与哪个最小值配对?

Update:

更新:

The basic logic that I mentioned in this post can be seen in this jsfiddle. However, I have not really worked on this much - I am looking for the logic to basically link sets of min and max fields the way I described. And I don't know if this is the best way to do this - as I mentioned, I'd love to be able to do this generically so that I don't have to refer to the min and max fields by id.

我在这篇文章中提到的基本逻辑可以在这个 jsfiddle 中看到。但是,我并没有真正做过这么多工作 - 我正在寻找基本按照我描述的方式链接最小和最大字段集的逻辑。而且我不知道这是否是最好的方法 - 正如我所提到的,我希望能够通用地做到这一点,这样我就不必通过 id 来引用 min 和 max 字段。

回答by Andrew Whitaker

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

好的,这里有一些应该起作用的东西。该规则基于内置equalTo方法:

$.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/

示例:http : //jsfiddle.net/tUPQc/2/



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

为了使规则更通用,您必须使用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:

然后在你的 HTML 中:

<input id="maxTruck" name="maxTruck" type="text" class="number greaterThan" data-min="minTruck" />

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

示例:http : //jsfiddle.net/tUPQc/3/

回答by user2964333

Simple and good way to use addmethod

使用 addmethod 的简单好方法

$.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());
}, "Must be greater than to field 1");

validating code

验证码

filed2_name: {

            greaterThan: '#filed1_id'
        },  

second i prefer first

第二我更喜欢第一

$.validator.addMethod('le', function(value, element, param) {
      return this.optional(element) || value <= $(param).val();
}, 'Invalid value');
$.validator.addMethod('ge', function(value, element, param) {
      return this.optional(element) || value >= $(param).val();
}, 'Invalid value');

$('form').validate({rules: {
            fieldName1: {le: '#fieldID2'},
            fieldName2: {ge: '#fieldID1'},
             ...
      },
      messages: {
            fieldName1: {le: 'Must be less than or equal to field 2'},
            fieldName2: {ge: 'Must be greater than or equal to field 1'},
            ...
      }
});