javascript 使用 jquery.validate 数据注释验证数字范围

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

Validate for number range using jquery.validate data annotations

javascriptjqueryjquery-validate

提问by Travis J

When constructing an input an ASP.NET MVC 3 view which uses jQuery.validate

构造输入时使用 jQuery.validate 的 ASP.NET MVC 3 视图

<input 
  type="text" 
  class="text-box single-line" 
  id="ReserveQuantity" 
  name="ReserveQuantity" 
  data-val="true" 
  data-val-required="The Reserve Quantity field is required." 
  data-val-number="This value must be numeric"
>

this is markup that would be used for for a ReserveQuantity input. In addition to these parameters, what data-annotation should I use in order to make sure only a certain numeric range is acceptable here without manual validation?

这是用于 ReserveQuantity 输入的标记。除了这些参数之外,我data-应该使用什么注释来确保这里只有特定的数字范围是可接受的,而无需手动验证

回答by Travis J

There is actually a built in data annotation for ranges, and it looks like this:

实际上有一个内置的范围数据注释,它看起来像这样:

data-val-range="The field must be in range 0 to 104." 
data-val-range-min="0" 
data-val-range-max="104"

回答by nbrooks

http://docs.jquery.com/Plugins/Validation/Methods/range#range

http://docs.jquery.com/Plugins/Validation/Methods/range#range

var minVal = 10, maxVal = 20;

$("#myform").validate({
    rules: {
        ReserveQuantity: {
            required: true,
            range: [ minVal, maxVal ]
        }
    }
});