Search code examples
asp.net-mvc-3jquery-validatejquery-globalization

Localizing jquery validation with asp.net mvc 3


I am using Asp.Net Mvc3 and the unobtrusive jquery validation. I'd like to have my dates validation localized, I mean, jquery is validating my date as being MM/dd/yyyy but I would like it to be dd/MM/yyyy.

I'm trying to use the jQuery Globalize plugin (http://github.com/jquery/globalize). I added references to the scripts globalize.js and globalize.culture.pt-BR.js and when my page loads I'm running the follwing script:

(function() {
  $(function() {
    $.datepicker.setDefaults($.datepicker.regional['pt-BR']);
    Globalize.culture("pt-BR");
  });
}).call(this);

The jQuery UI plugin works as charm, but the validation doesn't. What else am I missing?

Edit:

Using the links in the answer below I solved the problem using the Globalize plugin:

Of course, I had to add a reference to the Globalize plugin in the page and also a reference to the culture that I wanted to use (all available on the plugin's site). After that is just a small piece of JavaScript code.

Globalize.culture("pt-BR");
$.validator.methods.date = function(value, element) {
    return this.optional(element) || Globalize.parseDate(value);
};

Solution

  • If you are doing any work with internationalization and ASP.NET MVC I highly recommend reading through these two excellent posts by Nadeem Afana

    In his second post he has a detailed example of using the jQuery UI datepicker and discusses the issues with localization.

    In his example he mentions the following

    @* Unfortunately, the datepicker only supports Neutral cultures, so we need to adjust date and time format to the specific culture *@
        $("#EventDate").change(function(){
          $(this).val(Globalize.format($(this).datetimepicker('getDate'), Globalize.culture().calendar.patterns.d + " " + Globalize.culture().calendar.patterns.t)); /*d t*/
        });
    

    i also recommend downloading the Nerd Dinner internationalization demo linked on his site.