jQuery 验证 - 在运行时更改最小最大数量检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12476831/
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 11:43:30  来源:igfitidea点击:

jQuery validation - Change min max number checking at runtime

jqueryvalidation

提问by Dzung Nguyen

Can I change the min, max of a number's validation at runtime ?

我可以在运行时更改数字验证的最小值、最大值吗?

I use jQuery validation plugin.

我使用jQuery 验证插件

My simplified layout and structure to demonstrate how it should work. when I change the value of max range the max range's validation of the field number has to be changed too.

我的简化布局和结构来演示它应该如何工作。当我更改最大范围的值时,字段编号的最大范围验证也必须更改。

jsFiddle: http://jsfiddle.net/nXqd/qC2Ya/3/

jsFiddle:http: //jsfiddle.net/nXqd/qC2Ya/3/

Thanks

谢谢

采纳答案by techfoobar

Updated demo:http://jsfiddle.net/techfoobar/qC2Ya/5/

更新演示:http : //jsfiddle.net/techfoobar/qC2Ya/5/



You can do this by specifying minand maxoptions in your validation rules:

您可以通过在验证规则中指定minmax选项来做到这一点:

For ex:

例如:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      min: 13
    }
  }
});

API Docs:

API 文档

http://docs.jquery.com/Plugins/Validation/Methods/min#value

http://docs.jquery.com/Plugins/Validation/Methods/min#value

http://docs.jquery.com/Plugins/Validation/Methods/max#value

http://docs.jquery.com/Plugins/Validation/Methods/max#value

回答by Nope

Using this answerfrom another SO post as a guide I was able to change your code and get this to work.

使用另一个 SO 帖子中的这个答案作为指导,我能够更改您的代码并使其正常工作。

// Bind initial rule;
bindRangeRule(1, 2);

$("input[name='change-range']").on("keyup", function() {
    var value = $(this).val();

    // add some validation here off course to ensure only numbers are accepted.
    // You can do that by checking the event.keyCode values I believe.
    // If an invalid value was specified you can throw an alert
    // or simply clear the input field and return false. Or similar.

    // re-bind range rule
    bindRangeRule(1, parseInt(value));
});

function bindRangeRule(from, to) {
    var settings = $('form').validate().settings;

    delete settings.rules.number;

    settings.rules.number = {
        required: true,
        range: [from, to]
    }
};