To implement localization at client level we need to use Globalization plugin. Globalization plugin enables you to easily format date, currencies, decimals and numbers. It enables you to apply localization at client side.
Now if someone wants to apply localization on decimal field(which means it validate decimal at client side by taking care of culture we have selected)
E.g. we need to pass value 12.25 (as per EN culture) which is 12, 25(as per DK culture).
Now our text field must allow 12, 25 if DK culture is selected and allow 12.25 when EN culture is selected.
In order to achieve this you need to use Globalization.js. You just need to include reference of following described JavaScript files.
@Html.Script("~/Contents/Scripts/Shared/jquery.validate.js")
@Html.Script("~/Contents/Scripts/Shared/jquery.validate.unobtrusive.js")
@Html.Script("~/Contents/Scripts/Shared/globalize.js")
@Html.Script("~/Contents/Scripts/Shared/cultures/globalize.cultures.js")
<script src="@Url.Content("~/Contents/Scripts/Shared/cultures/globalize.culture." + System.Threading.Thread.CurrentThread.CurrentCulture + ".min.js")"></script>
Then we need to set culture we want to set in $(document).ready () as shown bellow:
$(document).ready(function ($) {
Globalize.culture('@System.Threading.Thread.CurrentThread.CurrentCulture');
});
After that we need to attach custom number validation method in client side that we have attached using data annotation in our model.
$.validator.methods.number = function (value, element) {
return this.optional(element) ||
!isNaN(Globalize.parseFloat(value));
}
Now as explain above someone wants to extend required validations one can achieve this as explain below:
$.validator.methods.required = function (value, element, param) {
if (value.charAt(0) == ' ') {
value = value.trim();
element.value = value;
return false;
}
return true;
}
Now as explain above someone wants to extend range validations one can achieve this as explain below:
jQuery.extend(jQuery.validator.methods, {
range: function (value, element, param) {
var val = Globalize.parseFloat(value);
return this.optional(element) || (val >= param[0] && val <= param[1]);
}
});
When someone wants to display calculated value as per culture use function given bellow:
Globalize.format(val, format)
Val: value to be formatted
Format: Format to which you want to set value
Returns formatted value.
Now if someone wants to convert decimal value displayed culture wise then he need to use:
Globalize.parseFloat(Val)
Val: Value to be parsed
Returns float value if conversion is successful otherwise return NaN.
You can refer this blog for more information :http://weblogs.asp.net/scottgu/jquery-globalization-plugin-from-microsoft
and
http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx
and
http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx