Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 453
Dismissile Avatar asked Sep 28 '11 16:09

Dismissile


2 Answers

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.") 
like image 117
Jared Peless Avatar answered Sep 30 '22 21:09

Jared Peless


Try this,

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

Hope this will help you.. :)

like image 43
K.Kirivarnan Avatar answered Sep 30 '22 20:09

K.Kirivarnan