client-side validation trips on DataAnnotation Range attribute

风格不统一 提交于 2019-11-27 15:37:49

We are having the same problem with jQuery.validate 1.11.0 and Microsoft.jQuery.Unobtrusive.Validation 2.0.30116.0. Somewhere in the validation library updates, the number validator broke.

There is an open issue on the GitHub issue tracker relating to this problem: https://github.com/jzaefferer/jquery-validation/issues/626

Quoted in that issue:

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]) );

I have changed my copy of 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]));
},

Now the range operations work as intended using DataAnnotations:

[Range(1, 100)]
public decimal Price { get; set; }

Microsoft issued an update to microsoft.jQuery.Unobtrusive.Ajax and to microsoft.jQuery.Unobtrusive.Validation (from version '2.0.20710.0' to '2.0.30116.0') that fixes both .live and validation problems

This happening because you have updated Jquery version and new version of Jquery has different new updates and they have also removed some function like .live and replaced it with .on

Go through it...

http://jquery.com/upgrade-guide/1.9/#live-removed

I run into this recently. I upgraded from MVC 2 to MVC 5. It seems that parameter name was changed from "minimum" and "maximum" to "min" and "max"

If you want to fix the issue without going through the hassle of upgrading your JavaScript files, search in your solution for these two lines and replace them with the better line

rule.ValidationParameters['minimum']

replace with

typeof(rule.ValidationParameters['minimum'])!='undefined'?rule.ValidationParameters['minimum']:rule.ValidationParameters['min']

and

rule.ValidationParameters['maximum'];

with

typeof(rule.ValidationParameters['maximum'])!='undefined'?rule.ValidationParameters['maximum']:rule.ValidationParameters['max']

Or alternatively, replace "RangeValidator" function with this code

Sys.Mvc.RangeValidator.create=function(rule){var $0=typeof(rule.ValidationParameters['minimum'])!='undefined'?rule.ValidationParameters['minimum']:rule.ValidationParameters['min'];var $1=typeof(rule.ValidationParameters['maximum'])!='undefined'?rule.ValidationParameters['maximum']:rule.ValidationParameters['max'];return Function.createDelegate(new Sys.Mvc.RangeValidator($0,$1),new Sys.Mvc.RangeValidator($0,$1).validate);}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!