While working with MVC 3, I hit some problems with validation. MVC 3 uses jQuery validation plugin with unobtrusive validation to help you out. Except when I had to use Finnish formatted numbers, there was a problem. jQuery/javascript did not really like the comma as a decimal separator.
A similar problem is with the range validation, which also refuses to work when using a comma as the decimal separator.
A rather nasty set of problems I might say, especially since number validation rules are added AUTOMATICALLY by ASP.NET MVC if you render a TextBox for a Decimal field in the model. It just seems the writer of the validator plugin forgot about everyone outside US (thanks @Deef for this last comment).
Fixing jquery.validate.js
You can of course go into the source of the validator javascript file and make your changes there, but modifying this file should never be done directly. That would create all kinds of nasty problems when updating to future versions.
Instead, one should take advantage of extending (replacing) the validator functions that are provided by jQuery Validate. (thanks to @ruben for the information on this).
To fix these problems, we can take the default implementation from the jquery.validate.js file for the range() and number() functions. We then create another .js file (say jQueryFixes.js), in which we override these default functions with ones that contain support for the comma as a decimal separator. The contents of the file should be something like this:
$.validator.methods.range = function (value, element, param) { var globalizedValue = value.replace(",", "."); return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]); } $.validator.methods.number = function (value, element) { return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value); }
This should be the last .js file you include, so it overrides the behavior of the default functions from the jQuery Validator plugin.
For number validation, what we have done is replace the last dot with an expression that also accepts a comma (change is bolded):
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:[\.,]\d+)?$/.test(value);
This will solve the number validation problem with the decimal point/comma. If you are dealing with thousand separator, you might need to tweak this further.
As for the range validation, I opted to simply replace the comma with a dot, and proceed normally from there on. You could of course use the jquery globalization plugin, please see the comments section for @ruben's recommendation on that one.
And that is about it. Now decimal separator commas should also be accepted by the validators.
@ Thursday, 13 May 2021 10:11