I am trying to have my client side validation (model binding) to support different cultures, and I found an interesting blog on the subject on which I am trying to implement
I've just fixed this issue replacing the line 1050 of the jquery.validate.js with this code:
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:[.|\,]\d+)?$/.test(value);
I've just changed smth on the regular expression used to validate the number and now it's working great!!
Try this it's slightly modified version:
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
//if with period use InvariantCulture
if (valueResult.AttemptedValue.Contains("."))
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.InvariantCulture);
}
else
{
//if with comma use CurrentCulture
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
It works for me.
UPDATE
If you're using a partial view use $.validate.unobtrusive.parse("#selector")
to reapply validation. If not try setting a globalization in your web.config (one in the root, not in the Views) to something like this:
<configuration>
<system.web>
<globalization fileEncoding="utf-8"
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="hr-HR" uiCulture="hr-HR" />
</system.web>
</configuration>
I have globalization set to Hr where we use comma as delimiters but with the DecimalModelBinder i have posted it will properly parse decimal or comma. Regards
Finally, by understanding that the Custom DecimalModelBinder would only handle server-side validation and not affect the jquery.validate.js which handles the client-side validation, I found a solution to the problem.
Extending the validation solved my issue.
Extend the validation by a new .js file as a workaround to the problem:
$.validator.methods.number = function(value, element) {
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/ .test(value);
};
This blog was really helpful http://rebuildall.umbraworks.net/2011/03/02/jQuery_validate_and_the_comma_decimal_separator