How to change default validation error message in ASP.NET MVC?
Asked Answered
P

1

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')]

Pronghorn answered 2/6, 2011 at 11:42 Comment(0)
P
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.

Pronghorn answered 2/6, 2011 at 13:12 Comment(6)
Helpful, thx. Seems that the issue isn't solved even in MVC3 which is sad. So what does ErrorMessage for DataType attribute do?Saunders
Its too heavy that we need to do add resx file for this. :(Armipotent
We have switched to MVC3 and then MVC4, no problems so far.Pronghorn
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.thanksCollier
@mahdigh you can ask it as a SO question so everyone can chip in troubleshooting it?Pronghorn
here is the link for my question.please take a look.thanks #18330920Collier

© 2022 - 2024 — McMap. All rights reserved.