client-side validation trips on DataAnnotation Range attribute

后端 未结 4 1375
北海茫月
北海茫月 2020-12-03 22:32

I have the following code in my Model class:

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

After recent upgrade (I assume) of

4条回答
  •  青春惊慌失措
    2020-12-03 23:30

    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; }
    

提交回复
热议问题