Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 539
Sedat Kapanoglu Avatar asked Jun 02 '11 11:06

Sedat Kapanoglu


People also ask

How remove validation message after field is valid in MVC?

So, to clear the validation errors, you can do something like this to a form : var fieldContexts = form. __MVC_FormValidation. fields; for(i = 0; i < fieldContexts.

How do you show custom validator error message in validation summary?

In order for the Validator 's error message to display in the ValidationSummary , you need to set the Validator s Display="none" .

How can show validation message in ASP.NET MVC?

You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary() method returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.


1 Answers

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.

like image 62
Sedat Kapanoglu Avatar answered Oct 17 '22 02:10

Sedat Kapanoglu