Glogalizing jQuery Validation for Number and Date

The jQuery validation and the jQuery unobtrusive validation are frameworks for client validation. The default implementation uses the en-US culture, that is, number in the format of dot deparating the decimal places and date in the format MM/dd/yyyy. In this post we will customize that according with the culture chosen by the user.

The last post the culture chosen by the user was in a cookie called “language”, this post I´ll use the same cookie, but again, feel free to put and use the culture information as you want.

The first step is to open the Nuget Package Manager Console and type “Install-Package jquery-globalize -Version 0.1.3.”

Now create a new javascript file called setup-globalization.js in the Scripts folder with the content below.

; (function ($) {
    // this method is a copy from http://www.w3schools.com/js/js_cookies.asp
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
        }
        return "";
    }

    var language = getCookie("language");

    if (language == "") {
        language = "en-US";
    }

    $("body").append("<script type='text/javascript' src='/Scripts/globalize/globalize.js'></script>");
    $("body").append("<script type='text/javascript' src='/Scripts/globalize/cultures/globalize.culture." + language + ".js'></script>");

    $.validator.methods.number = function (value, element) {
        if (value == "" || Globalize.parseFloat(value, null, Globalize.cultures[language])) {
            return true;
        }
        return false;
    }

    $.validator.methods.date = function (value, element) {
        if (value == "" || Globalize.parseDate(value, null, Globalize.cultures[language])) {
            return true;
        }
        return false;
    }

})(jQuery);

First we try to get the specified language from the cookie, if it is empty we set the default en-US.

Next we add the globalize.js and the globalize.culture.[culture from cookie].js, the first file has the core implementation, and the second customize the formats.

Finally we customize the validator number and date methods, now every time the jQuery validation tries to validate a number or datetime, our methods will be called.

Now open the page and include this new file below the jQuery, jQuery Validate and jQuery Validate Unobtrusive.

<script src="/Scripts/jquery.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="/Scripts/setup-globalization.js"></script>

That´s it, now you have a globalized validation!

Anúncios
Glogalizing jQuery Validation for Number and Date

2 comentários sobre “Glogalizing jQuery Validation for Number and Date

    1. Olá Sergio, segue exemplo:


      $.validator.methods.range = function (value, element, params) {
      if ($(element).val() == "") {
      return true;
      }

      var value = Number($(element).val().replace(/\./g, "").replace(",", "."));

      if (isNaN(value) == true) {
      return false;
      }

      return value >= params[0] && value <= params[1];
      }

      $.validator.methods.min = function (value, element, params) {
      value = Number($(element).val().replace(/\./g, "").replace(",", "."));
      return this.optional( element ) || value >= param;
      }

      $.validator.methods.max = function (value, element, params) {
      value = Number($(element).val().replace(/\./g, "").replace(",", "."));
      return this.optional( element ) || value <= param;
      }

      Aconselho abrir o arquivo jquery.validate.js e procurar por minlength ou rangelength, etc, você verá todos os métodos possíveis l$aacute;.

      Att.

      Curtir

Deixe uma resposta para Sergio Cancelar resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Foto do Google

Você está comentando utilizando sua conta Google. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s