30

Say I have this property in my model:

[DisplayName("test")]
[Required(ErrorMessage = "required")]
public DateTime? SomeDate { get; set; }

when you type in "asdf" in Html.TextBoxFor(model => model.SomeDate), you get the validation error message "The value 'asdf' is not valid for test.".

How do you modify that message? ASP.NET MVC ignored [DataType(DataType.DateTime, ErrorMessage = 'some other message')]

Anders Abel
  • 67,989
  • 17
  • 150
  • 217
Sedat Kapanoglu
  • 46,641
  • 25
  • 114
  • 148

1 Answers1

30

Apparently my question was already answered at How to replace the default ModelState error message in Asp.net MVC 2? .

I'll summarize it here:

  • Create App_GlobalResources folder for your project (right click to project -> Add -> Add ASP.NET folder -> App_GlobalResources).
  • Add a resx file in that folder. Say MyNewResource.resx.
  • Add resource key PropertyValueInvalid with the desired message format (e.g. "content {0} is invalid for field {1}"). If you want to change PropertyValueRequired too add it as well.
  • Add the code DefaultModelBinder.ResourceClassKey = "MyNewResource" to your Global.asax startup code.

You're all set.

Community
  • 1
  • 1
Sedat Kapanoglu
  • 46,641
  • 25
  • 114
  • 148
  • 2
    Helpful, thx. Seems that the issue isn't solved even in MVC3 which is sad. So what does ErrorMessage for DataType attribute do? – rafek Feb 18 '12 at 05:38
  • 3
    Its too heavy that we need to do add resx file for this. :( – kbvishnu Nov 29 '12 at 09:57
  • We have switched to MVC3 and then MVC4, no problems so far. – Sedat Kapanoglu Aug 22 '13 at 07:53
  • i created a new mvc 3 project, and did all of the steps. even i changed the resource file to embedded resource, but still shows "The User name field is required" for the default AccountController. please tell me what to do? or if you can make mvc3 sample.I'm sure there are a lot of people who have this problem.thanks – mahdi gh Aug 25 '13 at 06:53
  • @mahdigh you can ask it as a SO question so everyone can chip in troubleshooting it? – Sedat Kapanoglu Aug 26 '13 at 13:24
  • here is the link for my question.please take a look.thanks http://stackoverflow.com/questions/18330420/how-to-change-validation-error-messages-in-mvc-3 – mahdi gh Aug 27 '13 at 04:40