Jquery Validation has a serious bug on numeric fields where the first character is a decimal
i am using asp.net-mvc3 helpers and the jquery validation开发者_JS百科 plugin (what comes out of the box when you use the templates (Create, Edit, etc . .) and i have a field called MiniPrice that is a dataType decimal?
so it validates on the client side that i enter a number in the textbox.
if i enter 1.25 it works fine. If i enter 0.75 it works fine, but if i enter .75 it give this validation error:
why does the jquery unobtrusive validation think .75 isn't a valid number?
I found this bug that was filed years ago on the jquery core site and it was closed as not a jquery core issue but rather a plugin issue.
That appears to be how the validator behaves. I'd open an issue with jQuery to see if they can (or want) resolve it.
In the mean time, you can make your own validator method like so that it behaves as you would expect:
$.validator.addMethod('myValidateNumber', function (value) {
return /^(\d\.|\.)?\d+$/.test(value);
}, 'Please enter a valid number');
This regex appears to do what you desire - there is likely a better way to write it as well. I am no regex master, but this should suffice.
Then just use myValidateNumber
in the class
of whatever you are validating. You can read more about extending jQuery validation here.
EDIT: To wire this in to MVC3 - take a look at this StackOverflow post: Perform client side validation for custom attribute.
Essentially what we are doing is creating our own validation for this, and you can apply your own attribute to the model.
EDIT 2: It appears that if you use validator.addMethod('number'...
, it will change the default behavior of the numeric validation. This means you shouldn't have to change your MVC Model at all. So basically, adding this to your page load:
$.validator.addMethod('number', function (value) {
return /^(\d\.|\.)?\d+$/.test(value);
}, 'Please enter a valid number');
Should resolve the problem.
精彩评论