Last post Feb 23, 2010 10:44 AM by elspinos
Feb 22, 2010 11:01 AM|elspinos|LINK
Greetings fellow MVC developers,
I've subclassed the RequiredAttribute with am implementation that leverages existing localization resources. When I use my subclassed attribute, the client side validation code generated MVC when Html.EnableClientValidation() is invoked doesn't work as
it fails to recognise the parent RequiredAttribute type.
I've tried to override the GetType() method to try and cloak my subclass and this didn't work. I've also had a look at some of the solutions out there for implementing a localizable RequiredAttribute where some solutions require you to subclass it or implement
a provider which I already have. For the purpose of my implementation, another layer of localization is not an option.
Here is my implementation of the RequiredAttribute subclass leveraging a localization provider:
public class RequiredLocalizableAttribute : RequiredAttribute
public RequiredLocalizableAttribute(string literalKey)
ErrorMessage = this.GetLiteralFor(literalKey);
When I attribute a model property with the above, client side validation is broken, however, with the original RequiredAttribute class, client side validation works as expected.
Does anyone have a workaround to solve this issue or would it be suitable to recommend that the code that generates the client side validation scans the inheritance hierarchy for a RequiredAttribute type and morph my subclass into the base class...
DataAnnotations RequiredAttribute EnableClientValidation client validation
Feb 22, 2010 06:46 PM|levib|LINK
Don't forget to register your custom attribute with the validation provider:
The RequiredAttributeAdapter is what provides the [Required] client-side hookup, so this call just tells the validator to associate your server-side adapter with that client-side code. Do this from within Global.asax.
Feb 22, 2010 10:43 PM|ricka6|LINK
I have a full sample at
see Custom Client Validation
Feb 23, 2010 10:44 AM|elspinos|LINK
Thanks for the assistance. Registering the subclass validation attribute types to their adaptors as described solved the problem.
I also tested this in the static constructor of the attribute subclass and it works as expected.
Thanks for the resource, your samples demonstrate additional ways to implement custom validation and I’d recommend that people visiting this thread take a look at the Custom Client Validation and Custom Remote Client Validation samples as an additional resource
to fully customising their models.