Date problem with globalize.js and jquery.validation.globalize.js. How to resolve?

Asked

Viewed 6,870 times

12

I’m having problems with the date fields of my application.

Campos data

Follow this answer that seemed more appropriate, Datetime field error message, I configured my ASP.NET MVC application as follows:

  1. I installed the jquery-globalize package via Install-Package jquery-globalize;
  2. I installed the package jquery.validation.globalize via Install-Package jquery.validation.globalize;

    estrutura dos arquivos estáticos

  3. I added the tab to Web.config reference to the language en.

    <system.web>
        ...
        <globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true"
            requestEncoding="UTF-8" responseEncoding="UTF-8" fileEncoding="UTF-8" />
        ...
    </system.web>
    

Although in the answer indicates to add in <configuration>, the application was error in Web.config file and then I got in tag <system.web>.

  1. I set up my Bundleconfig.Cs:

    BundleConfig.cs

  2. I organized my scripts according to the example of the answer, leaving so:

    scripts

    The script with Globalize.culture("pt-BR"); at the end of the picture was a last attempt I made.
    jquery.validation.js loads through other views, when needed, via @section footerSection{ Scripts.Render("~/js/jqueryval"); }. So, my output of the scripts is like this, in debug mode:

    ordem dos scripts em output - modo debug

  3. This is the properties of my View Model used to render the fields:

    [DataType(DataType.Date)]
    [DisplayName("Data Vencto.")]
    [Required(ErrorMessage = "Informe o campo {0}")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? txtDataVencimento { get; set; }
    
    [DataType(DataType.Date)]
    [DisplayName("Data Pagto.")]
    [Required(ErrorMessage = "Informe o campo {0}")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? txtDataPagamento { get; set; }
    

    I’ve tested with DataFormatString = "{0:yyyy-MM-dd}", but it didn’t work either.

  4. Razor:

    <div class="form-group">
        @Html.LabelFor(model => model.txtDataVencimento, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.txtDataVencimento, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.txtDataVencimento, "", new { @class = "text-danger" })
        </div>
    </div>
    
    <div class="form-group">
        @Html.LabelFor(model => model.txtDataPagamento, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.txtDataPagamento, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.txtDataPagamento, "", new { @class = "text-danger" })
        </div>
    </div>
    

So I ask you for help: What may still be missing or wrong?


EDITION

According to the response of Gypsy Morrison, the order of my scripts should be another and so I applied the Bundle as given guidance.

var bundle = new ScriptBundle("~/js/jqueryval") { Orderer = new AsIsBundleOrderer() };
bundle
    .Include("~/Static/js/jquery.validate.js")
    .Include("~/Static/js/jquery.validate.unobstrusive.js")
    .Include("~/Static/js/globalize/globalize.js")
    .Include("~/Static/js/jquery.validate.globalize.js");
bundles.Add(bundle);

With that my scripts were in the order indicated:

Nova ordem dos scripts

However, still the error continues, but demonstrating message in English: "Please enter a Valid date."

Nova mensagem de erro

Which was bold in black.


EDITION

When editing my Bugles to look like this:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/js/jquery").Include(
        "~/Static/js/jquery-{version}.js",
        "~/Static/js/jquery.plugin.js"));

    bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
        "~/Static/js/jquery.validate.js",
        "~/Static/js/jquery.validate.unobtrusive.js",
        "~/Static/js/globalize/globalize.js",
        "~/Static/js/jquery.validate.globalize.js"));

    bundles.Add(new ScriptBundle("~/js/bootstrap").Include(
        "~/Static/js/bootstrap.js"));


    bundles.Add(new StyleBundle("~/Static/css/styles").Include(
        "~/Static/css/bootstrap.css",
        "~/Static/css/site.css"));
}

And with the standard ordering done by Bundleconfig, my scripts stayed in that order:

Outra ordem dos scripts

The date validation passed, but the values went wrong:

outra validação com a nova ordem dos scripts

  • Hello, you forgot to implement CLDR file as the globalize depends on it. More information: http://cldr.unicode.org/, I made a small tutorial here : https://answall.com/a/227756/54019

1 answer

14


This is not a simple problem (it really consumed me the effort of a night to find out). The problem is the order of the js that needs to be respected:

  1. jquery.validate.js;
  2. jquery.validate.unobstrusive.js;
  3. globalize/globalize.js;
  4. jquery.validate.globalize.js.

Only that the standard implementation of ScriptBundle reorder even with the order specified correctly in Bundle.

The way is to implement a Bundle in order:

public class AsIsBundleOrderer : IBundleOrderer
{
    public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
    {
        return files;
    }
}

And then:

        var bundle = new ScriptBundle("~/bundles/jqueryval") { Orderer = new AsIsBundleOrderer() };

        bundle
            .Include("~/Scripts/jquery.unobtrusive-ajax.js")
            .Include("~/Scripts/jquery.validate-vsdoc.js")
            .Include("~/Scripts/jquery.validate.js")
            .Include("~/Scripts/jquery.validate.unobstrusive.js")
            .Include("~/Scripts/globalize/globalize.js")
            .Include("~/Scripts/jquery.validate.globalize.js");
        bundles.Add(bundle);

EDIT

In the case of numbers, it is necessary to work a little the numerical validator, which for some reason is not accepting comma:

// Esta parte pode ser colocada em um script da aplicação e juntado ao Bundle
jQuery.validator.addMethod("mynumber", function (value, element) {
    return this.optional(element) || /^(\d+|\d+,\d{1,2})$/.test(value);
}, "O campo " + element + " deve ser um número.");

// Esta parte é para cada form
$("#meuForm").validate({
    rules: {
        field: {
            required: true,
            mynumber: true
        }
    }
});

Or as the questioner suggested, use the Cleyton Ferrari example, which is more or less the same thing.

  • 1

    Thanks for the help! I implemented your template for the Bundle and got the order of the scripts as you said. But it still gives the same error. The difference is it’s in English: Please enter a valid date.. I will edit my question with this information.

  • 1

    Edits made. The last I found interesting.

  • @Severo I updated the answer.

  • In order not to have to write more scripts for my Forms I decided to use the methods_en-BR.js as found on the web but only for number, because with the date also the date problem occurred again. But finally, problem solved. Grateful!

  • @Severo Can you please pass me his link so I can update the answer?

  • On several sites I have already found this plugin, but here is an example of it: cleytonferrari, tigo in Technet.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.