With the help of @DanS I was able to elaborate a solution for the Date Validation for my country, Portugal (pt-PT) and here is the complete solution for anybody that have a problem validating a date:
First of all, you need to install the nuget package:
http://www.nuget.org/packages/jquery-globalize/
Then include in the page where you want to make the validation (or in the Bundle like me) the links to the core library and your country's culture file (note:put always first the core and then the culture file or else you will get an undefined error)
bundles.Add(new ScriptBundle("~/bundles/saida").Include(
"~/Scripts/Presenter/Saida/create.js",
"~/Scripts/Globalize/globalize.js",
"~/Scripts/Globalize/Cultures/globalize.culture.pt-PT.js",
"~/Scripts/Common/date.js"));
Set the Model:
[Required(ErrorMessage = "Preenchimento obrigatório.")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
[Display(Name = "Data da DAU")]
public DateTime? DAUData { get; set; }
I did not put any ErrorMessage in the DataType property because it's not passed to the View, instead, you can put a custom message in the View:
<div class="editor-field">
@Html.EditorFor(model => model.DAUData)
@Html.ValidationMessageFor(model => model.DAUData, "Formato de data inválido.")
</div>
But if you use the jQuery datepicker function with the definition of the format, you don't need to worry about the format:
$(function ()
{
$(".datefield").datepicker({ dateFormat: 'dd-mm-yy', changeYear: true });
});
The property changeYear is to presente a dropdown to choose the year (not mandatory, only a nice option to garanty that the value is always valid), and don't forget to inlcude the jQuery and jQueryUI references in your file to presente the calendar correctly.
To complete the client side script, I have the culture's format validation:
$.validator.methods.date = function (value, element)
{
return this.optional(element) || Globalize.parseDate(value, "dd-MM-yyyy", "pt-PT");
}
I also have a template for the date format in the View (place it in the Shared/EditorTemplates/ folder and don't forget to user the @Html.EditorFor razor method in the View:
@{
var value = "";
if (Model.HasValue)
{
value = String.Format("{0:d}", Model.Value.ToString("dd-MM-yyyy"));
}
}
@Html.TextBox("", value, new { @class = "datefield", type = "text", autocomplete = "off" })
Now anytime that you will need a date, use the Template, and the class "datepicker", and that's it!
Thanks again DanS ;)