How to configure ASP.NET MVC validation to accept dates pt-BR?

2

I can not set the formatting of dates on my forms. I've tried several cases, all using the same view:

@Html.EditorFor(model => model.Data, new { htmlAttributes = new { @class = "form-control" } })

Case 1: Clean and raw

public DateTime Data { get; set; }

Result:
It accepts everything, it does not validate at all. And it brings the complete date, even in the views where I used @Html.DisplayFor(modelItem => item.Data) . I wanted the abbreviated pt-BR.

Case 2: Using Annotation DataType

[DataType(DataType.Date)]
public DateTime Data { get; set; }

Result:
Improved, now format the date (including in the views I used DisplayFor() ), but in a view with data it does not show them and dd/mm/aaaa . I fill in with any date by typing or selecting in the datapicker and it accepts and overwrites the saved date.

Case 3: Using DataType and DisplayFormat

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[Required(ErrorMessage = "Informe a data deste lançamento.")]
public DateTime Data { get; set; }

Result: Visually perfect. In the views that I used DisplayFor() was as it wanted and when I open a view with EditorFor() the field displays the date summarized, formatted and with the datapicker. But when you change the date the validation does not accept the reported date in any way.

I broke my head for two days looking for a solution, I'm using NuGet's Globalization with culture set to Web.config and I'd like to do it in the most academic way possible (ie directly in the model or at most passing some attribute to the component in the view, avoiding as much as possible to change the existing default Javascript).

    
asked by anonymous 18.09.2015 / 21:17

1 answer

3

You missed adding jQuery.Validation.Globalize in your project and referencing it in BundleConfig .

This will possibly bring an extra problem: Your DateTime will appear as YYYY-MM-DD . This is because DisplayTemplate (using @Html.DisplayFor() ) uses what is in the DisplayFormat attribute, so we have to override this behavior.

Step 1: Create the directory DisplayTemplates

It stays inside ~/Views/Shared .

Step 2: Create the template of DateTime

Within this directory, create a View named DateTime.cshtml with the following:

@model DateTime?

@if (Model.HasValue)
{
    @Convert.ToDateTime(Model).ToString("dd/MM/yyyy")
}
    
18.09.2015 / 22:07