Customize the Error Message for an invalid date in ASP.net MVC

Dismissile picture Dismissile · Sep 28, 2011 · Viewed 14.3k times · Source

I have an ASP.net MVC model with a date:

public class EditModel
{ 
    [Display(Name="DOB")]
    public DateTime? DateOfBirth { get; set; }
}

@Html.TextBoxFor(m => m.DateOfBirth)
@Html.ValidationMessageFor(m => m.DateOfBirth)

When the user enters an invalid date such as 9/31/2011, the error message comes back as this:

The value '9/31/2011' is not valid for DOB.

This is happening when it is trying to do the model binding and is not one of my validations. Is there a way to customize this error message? I would like it to be something like:

Please enter a valid date for the Date of Birth.

I am not requiring the user to enter the Date, but when they do enter an INVALID value then I want to customize the error.

Answer

Jared Peless picture Jared Peless · Sep 28, 2011

You can use data annotations for errors, or, in this case you can do this:

@Html.ValidationMessageFor(m => m.DateOfBirth , "Please enter a valid date for the Date of Birth.")