Search code examples
c#asp.net-mvcasp.net-mvc-validation

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


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.


Solution

  • Try this,

    [DataType(DataType.Date, ErrorMessage = "Please enter a valid date.")]
    public System.DateTime DateOfBirth { get; set; }
    

    Hope this will help you.. :)