Localizing jquery validation with asp.net mvc 3

2019-01-30 15:51发布

问题:

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);
};

回答1:

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

  • ASP.NET MVC 3 Internationalization
  • ASP.NET MVC 3 Internationalization - Part 2 (NerdDinner Demo)

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.



回答2:

I've been doing similar myself recently. I started by following the advice in Scott Hanselman's blog on this topic - you can read about this here:

http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx

I had to make some changes to use Globalize instead of jQuery Global (now jQuery Global is dead). I wrote this up in the following blog post in case that's helpful:

http://icanmakethiswork.blogspot.co.uk/2012/09/globalize-and-jquery-validate.html

My blog post features a link to this script jquery.validate.globalize.js which forces jQuery Validate to use Globalize for number / date / range parsing. The date part of this is the part that should probably solve your issue:

https://raw.github.com/gist/3651751/68cbccd0fdd4725a8d6fd1b5568bb33d27fb1eff/jquery.validate.globalize.js

/// <reference path="jquery-1.7.2.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="globalize.js" />

/*!
* Monkey patch for jquery.validate.js to make use of Globalize.js number and date parsing
*/

$(document).ready(function () {

    var currentCulture = $("meta[name='accept-language']").prop("content");

    // Set Globalize to the current culture driven by the meta tag (if any)
    if (currentCulture) {
        Globalize.culture(currentCulture);
    }

    //Tell the validator that we want numbers parsed using Globalize.js
    $.validator.methods.number = function (value, element) {    
        if (Globalize.parseFloat(value)) {
            return true;
        }
        return false;
    }

    //Tell the validator that we want dates parsed using Globalize.js
    $.validator.methods.date = function (value, element) {
        if (Globalize.parseDate(value)) {
            return true;
        }
        return false;
    }

    //Fix the range to use globalized methods
    jQuery.extend(jQuery.validator.methods, {
        range: function (value, element, param) {
            //Use the Globalization plugin to parse the value
            var val = Globalize.parseFloat(value);
            return this.optional(element) || (val >= param[0] && val <= param[1]);
        }
    });

});


回答3:

Little correction of Johnny Reilly answer:

 $.validator.methods.number = function (value, element) {    
    if (Globalize.parseFloat(value)) {
        return true;
    }
    return false;
}

must be replaced with

$.validator.methods.number = function (value, element) {
    return !isNaN(Globalize.parseFloat(value));
}

for correct parsing of zero string ("0").

So entire code is:

/// <reference path="jquery-1.7.2.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="globalize.js" />

/*!
* Monkey patch for jquery.validate.js to make use of Globalize.js number and date parsing
*/

$(document).ready(function () {

    var currentCulture = $("meta[name='accept-language']").prop("content");

    // Set Globalize to the current culture driven by the meta tag (if any)
    if (currentCulture) {
        Globalize.culture(currentCulture);
    }

    //Tell the validator that we want numbers parsed using Globalize.js
    $.validator.methods.number = function (value, element) {    
       return !isNaN(Globalize.parseFloat(value));
    }

    //Tell the validator that we want dates parsed using Globalize.js
    $.validator.methods.date = function (value, element) {
        if (Globalize.parseDate(value)) {
            return true;
        }
        return false;
    }

    //Fix the range to use globalized methods
    jQuery.extend(jQuery.validator.methods, {
        range: function (value, element, param) {
            //Use the Globalization plugin to parse the value
            var val = Globalize.parseFloat(value);
            return this.optional(element) || (val >= param[0] && val <= param[1]);
        }
    });

});