I am trying to replace the default validation messages in MVC3 that are displayed when you fail to fill in a required field or fill in an invalid value. I am only addressing server-side validation in this question. My custom message for invalid value is working, but the one for missing required field won't apply.
This is what I have done:
Added an ASP.NET folder called "App_GlobalResources" to the web project, and in that folder I placed a resources file called "DefaultMessages.resx", containing the following keys and values:
PropertyValueInvalid: The value you input is invalid
PropertyValueRequired: This field is required
(These are not the actual messages I will be using; they will be in a different language, which is my primary reason for needing to replace the default ones.)
Registered the resource file with the DefaultModelBinder in Global.asax.cs like this (note I am using Ninject for dependency injection):
public class MvcApplication : NinjectHttpApplication { ... protected override void OnApplicationStarted() { ... DefaultModelBinder.ResourceClassKey = "DefaultMessages"; ... } ... }
In my model I have a DateTime property called ExpirationDate. Since DateTime is non-nullable, the property is implicitly required. PropertyValueInvalid works; my custom message is rendered in the form after I submit with an invalid value in the ExpirationDate field, such as 30.02.2014. But if I leave the field empty and submit, I only get the default "The ExpirationDate field is required".
What am I missing here? Is PropertyValueRequired not the right name? Or does it not apply to implicitly required properties? I also tried adding an explicit Required attribute in the Model, like this:
[Required]
public DateTime ExpirationDate{ get; set; }
But that makes no difference. What does work is adding a custom error message to the attribute, for example like this:
[Required(ErrorMessage = "We need a date here!")]
public DateTime ExpirationDate{ get; set; }
But I don't want to do that for all the required properties that typically just need a generic message. (I know I could reference the generic message in the resource file in the Required attribute instead of stating the message directly, but that still adds clutter to the Model that should not be necessary.)
DefaultModelBinder
required message on a resource file. Question answers MVC4 but same for MVC3 apparently. Already answered here stackoverflow.com/questions/12545176/… – dgarbacz