Localizing jquery validation with asp.net mvc 3

前端 未结 3 1339
野的像风
野的像风 2020-12-23 10:30

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

3条回答
  •  情书的邮戳
    2020-12-23 11:06

    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

    /// 
    /// 
    /// 
    
    /*!
    * 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]);
            }
        });
    
    });
    

提交回复
热议问题