Customizing ASP.NET MVC's Required Property Validation Messages

I recently got convention-based localization of display labels working with ASP.NET MVC, and this week, I wanted to get something similar working for required field validation messages. ASP.NET MVC3 shows a default validation message when a required field is not filled in, unless you specify a resource provider and the name of the resource key when you put the Required attribute on a property. Just like with the display value of labels, I wanted a convention based approach for this. I wanted ASP.NET MVC to look for a resource key with the NameOfModelClassNameOfPropertyrequired convention.

After some googling and browsing the MVC3 source code, I couldn't really find the hook I needed to make this happen, so I let it rest for a few days and got back to it later on. I had more luck the second time around and found the hook I needed. ASP.NET MVC uses the RequiredAttributeAdapter class to retrieve a ModelClientValidationRequiredRule which by default is initialized with the default error message. The trick was just to inherit from this class and return a ModelClientValidationRequiredRule with your own message, and then register that class with the DataAnnotationsModelValidatorProvider. This is the new subclass of the RequiredAttributeAdapter class:

And this is how you tell ASP.NET MVC to use it:

And that's it... with this approach you have full control over how the message is formatted.

Written by Davy Brion, published on 4/3/2011 7:45:01 PM
Categories: asp-net-mvc

« Who Needs Classes Anyway? Automatically Including Current Language In Generated URLs With ASP.NET MVC »

comments powered by Disqus