Blog

How to implement custom validation logic using attributes in MVC3

By Carlos Martinez

A common (and very recommended) practice when working with model validation in MVC3 is to decorate the model that will be sent to the view with validation attributes.  In order to do this MVC3 has several validation attributes ready to use for this scenarios such as:

·         DataTypeAttribute

·         RangeAttribute

·         RegularExpressionAttribute

·         RequiredAttribute

An easy way to implement custom validation is to create attributes that inherits the ValidationAttribute

 class and add logic to the IsValid Method.

1

Adding code in this point will add server validations to the model (once the values are filled in the model throu a ModelBinder this validations will be executed), but this code is not gone to add anything to the view in order to make validations on the client side. In order to accomplish this is necessary to create a new ModelValidator.

This model validator will establish the validation rules that should be implemented on the client side in order to validate the field. The base class for model validator is DataAnnotationsModelValidator

2
This attribute should override the GetClientValidationRules method, and will specify all the validation rules (see jQuery validation) such as required, date, number, currency, etc. Now, the only thing that is missing is to register this new attribute adapter in the global application file.
3

Now that this is done, when a property is decorated with our new attribute, MVC will render all the validation requirements in order to make all the client validations, no further code will be needed.

Here are some points to consider when working with client validations:

·         For all not nullable values, MVC adds the “required” validation rule, so when working with this kind of values no further “required” validation rule should be added.

·         Also, in order to render the validation rules into the view, it is necessary to work inside a form tag, because is a form context is always necessary for MVC to render validation controls

 

Comments

Leave a comment

 
 
 
 
CAPTCHA Image Validation