Reputation: 23655
I've read a lot of blogposts about this subject, but I never saw the complete solution.
I've scaffolfed this default html (where bedrag is a Decimal):
<div class="editor-field">
@Html.EditorFor(model => model.Bedrag)
@Html.ValidationMessageFor(model => model.Bedrag)
</div>
This generates a comma for the decimal in the input control when the page is rendered, even when I put this in my web.config:
<globalization culture="en-US" uiCulture="en-US" />
or this one
<globalization culture="auto" uiCulture="auto" />
Then, the Jquery Validation plugin complains that I have a comma as decimal separator in my 'bedrag' input field (which has been put there by the @Html.EditorFor(model => model.Bedrag)
), which gives the error my input is not a number; it expects a dot as a decimal separator.
But, when I enter the number as this 12.90, the defaults modelbinder converts my input to 1290 (input times 100).
Then I created a custom modelbinder, and in that code, the currentculture is 'nl-NL', so not the 'en-US' from my web.config.
So now I'm wondering:
1 Do I still need a custom model binder in 2014?
2 Which culture is used when ASP.Net creates the value for @Html.ValidationMessageFor(model => model.Bedrag)
? (and why not the one from my web.config?)
3 How can I dynamicly set the culture to use for the @Html.ValidationMessageFor(model => model.Bedrag)
4 How can I dynamicly set the culture to use for the Jquery validation?
I've been out of ASP.Net MVC for a year, but can it be that in 2014 I still have these issues with decimal signs?
Upvotes: 2
Views: 1647
Reputation: 3075
The approach I used is to extend the jQuery validator. It is based on this blogpost. I setted the culture in the metadata to BE-nl. Since this is a pure Dutch website, I don't do any checks further on.
$(function () {
// Look in metatag what culture we want
// and set this as culture for the client side.
var data = $("meta[name='accept-language']").attr("content");
Globalize.culture(data.toString());
// Don't validate on keyup event because it will mess up
// the cursor when replacing values in a textbox.
$('form').each(function () {
var validator = $(this).data('validator');
if (validator) {
validator.settings.onkeyup = false;
}
});
// Belgianize/sanitize the numbers inserted
// 1 000 000 => 1000000
// 1.00 => 1,00
$.validator.methods.number = function (value, element) {
var s = value.replace(/\ /g, '').split('.').join(',');
if (s.split(',').length < 3) {
var number = Globalize.parseFloat(s);
if (!isNaN(number)) {
$(element).val(s);
return this.optional(element) || true;
}
}
return this.optional(element) || false;
};
});
I think I used this jQuery library for the globalization
Upvotes: 1
Reputation: 18974
I think using jQuery Globalization Plugin from Microsoft will solve your problem.
Upvotes: 0