我的Model类中有以下代码:
[Range(1,100)] public decimal Price { get; set; }
最近升级(我假设)jquery.validate到1.11.0后,即使输入有效值,我也收到错误.如果我在web.config中关闭客户端验证 – 工作正常.所有其他属性(StringLength,required)工作正常.生成的HTML如下(为清晰起见,添加了换行符):
<input class="text-Box single-line" data-val="true" data-val-number="The field Price must be a number." data-val-range="The field Price must be between 1 and 100." data-val-range-max="100" data-val-range-min="1" data-val-required="The Price field is required." id="Price" name="Price" type="text" value="" />
我很确定它之前有效…除了jquery.validate中的错误之外别无所求.
解决方法
我们遇到了与jQuery.validate 1.11.0和Microsoft.jQuery.Unobtrusive.Validation 2.0.30116.0相同的问题.在验证库更新的某个地方,数字验证器坏了.
GitHub问题跟踪器上存在与此问题相关的未解决问题:https://github.com/jzaefferer/jquery-validation/issues/626
引用该问题:
return this.optional(element) || ( value >= param[0] && value <= param[1] );
Because this line checks strings,not numbers. If I have a range between 30 and 200,and I want to validate 120,then the string 120 is lesser then string 30.
This line must be something like this:
return this.optional(element) || ( Number(value) >= Number(param[0]) && Number(value) <= Number(param[1]) );
我已经更改了jquery.validate.js的副本:
// http://docs.jquery.com/Plugins/Validation/Methods/range range: function( value,element,param ) { return this.optional(element) || (value >= param[0] && value <= param[1]) || (Number(value) >= Number(param[0]) && Number(value) <= Number(param[1])); },
现在,范围操作使用DataAnnotations按预期工作:
[Range(1,100)] public decimal Price { get; set; }