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

Asked

Viewed 2,708 times

2

I can’t get the date formatting right in my forms. I 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; }

Upshot:
Accepts everything, does not validate anything. And brings the full date, including in the views where I used @Html.DisplayFor(modelItem => item.Data). I wanted the abbreviated en-br.

Case 2: Using Datatype Annotation

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

Upshot:
Improved, now already formats the date (including in the views I used DisplayFor()), but in a data view it does not show and yes dd/mm/aaaa. I fill in 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 I used DisplayFor() and when I open a view with EditorFor() the field displays the summarized date, formatted and with the datapicker. But when you change the date the validation does not accept in any way the informed date.

inserir a descrição da imagem aqui

I broke my head two days looking for a solution, I’m using Nuget Globalization with Culture configured on Web.config and would like to do this in the most academic way possible (that is, directly in the model or at most passing some attribute to the component in the view, avoiding at most changing the existing standard Javascript).

  • You added jQuery-Validate-Globalize and Globalize to your solution?

  • I had not added jQuery-Validate-Globalize. I added and corrected the EditorFor(). But in the views I use DisplayFor() the date appears 2015-07-14.

  • Yes, it is true. I would like to complement this as an answer?

  • Yes, please. And thank you for your help!

1 answer

3


Failed to add the jQuery.Validation.Globalize and make reference to it in the BundleConfig.

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

Step 1: Create the directory DisplayTemplates

It stays inside of ~/Views/Shared.

Step 2: Create the DateTime

Inside this directory, create a View calling for DateTime.cshtml with the following:

@model DateTime?

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

Browser other questions tagged

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