I have applied Range(decimal, decimal,...) to my property in model. It does not validate .99, but validates 0.99.
How to allow the leading Zero?
It is a bug in number regexp in jquery.validate.js and jquery.validate.min.js files that are by default coming with ASP.NET MVC 3.
Here is the code from jquery.validate.js, line 1048:
// http://docs.jquery.com/Plugins/Validation/Methods/number
number: function(value, element) {
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
}
This function performs test of string against the number regular expression. To fix it, replace regexp with following one: /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.
This is a short version. Now here is the explanation:
Buggy ^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$ regexp reads as:
^-?
Beginning of line or string
-, zero or one repetitions
Match expression but don't capture it. [\d+|\d{1,3}(?:,\d{3})+]
Select from 2 alternatives
Any digit, one or more repetitions
\d{1,3}(?:,\d{3})+
Any digit, between 1 and 3 repetitions
Match expression but don't capture it. [,\d{3}], one or more repetitions
,\d{3}
,
Any digit, exactly 3 repetitions
Match expression but don't capture it. [\.\d+], zero or one repetitions
\.\d+
Literal .
Any digit, one or more repetitions
End of line or string
As you can see, second capturing group (?:\.\d+)? allows numbers in .XX format but when matching, first group (?:\d+|\d{1,3}(?:,\d{3})+) is checked first and validation fails because first group must be matched.
If we will reffer to the http://docs.jquery.com/Plugins/Validation/Methods/number demo and examine their regexp for number validation it will look as follows: ^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$. Which is same as buggy one but now first matching group should be of zero or one repetitions or optional in other words. And this additional ? in regexp fixes bug.
Edit: this also applies to MVC 4 default template. Both templates are using 1.9.0 version of plugin. In version 1.10.0 this issue was fixed. From changelog:
So sometimes staying updated is a good idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With