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

4

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.

Merth answered 28/9, 2011 at 16:6 Comment(0)
M
5

Try this,

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

Hope this will help you.. :)

Malaysia answered 15/12, 2011 at 8:25 Comment(0)
L
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.") 
Lauralee answered 28/9, 2011 at 16:10 Comment(2)
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.Merth
Then write a custom validator for it and put the message about the invalid date with that validator.Lauralee
M
5

Try this,

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

Hope this will help you.. :)

Malaysia answered 15/12, 2011 at 8:25 Comment(0)
T
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; }
}
Threatt answered 28/9, 2011 at 22:22 Comment(1)
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.Gonfanon
M
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

Muzzleloader answered 27/6, 2014 at 3:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.