9

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.

Dismissile
  • 32,564
  • 38
  • 174
  • 263

4 Answers4

5

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.") 
Jared Peless
  • 1,120
  • 9
  • 11
  • 1
    This would change it for all errors. I have other validations that I don't want to override. Also, I am currently using this because I want to display a * next to the text box and use the validation summary to show the full error. – Dismissile Sep 28 '11 at 16:14
  • Then write a custom validator for it and put the message about the invalid date with that validator. – Jared Peless Sep 29 '11 at 00:06
5

Try this,

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

Hope this will help you.. :)

K.Kirivarnan
  • 828
  • 9
  • 15
1
public class myClass()
{

    [Display(Name="Date of Birth"), DataType(DataType.Date, ErrorMessage = "Please enter a valid date for the Date of Birth.")]
    public string dateOfBirth { get; set; }
}
Ricky
  • 36
  • 2
  • 3
    FYI, it seems that ErrorMessage is ignored with the DataType attribute. It does show an error message, but not the one specified in the ErrorMessage parameter. See [MVC Datatype ErrorMessage](http://stackoverflow.com/questions/13916991/mvc-datatype-errormessage). – Nicholas Westby Mar 25 '14 at 17:45
0

With me error message in datatype not work Remove it using regular

[Display(Name="Date of Birth")]
[RegularExpression(@"^(3[01]|[12][0-9]|0[1-9])[-/](1[0-2]|0[1-9])[-/][0-9]{4}$", ErrorMessageResourceName = "DateNotValid", ErrorMessageResourceType = typeof(Resources))]
    public string dateOfBirth { get; set; }

DateNotValid : is using in resource file. you can change to error message if you want the format above for: dd-MM-YYYYY

Wolf
  • 6,361
  • 2
  • 28
  • 25