This afternoon we did some work to update our corporate site to MVC 2. We are using the new System.ComponentModel.DataAnnotations attributes to decorate our domain entities and by doing so you‘ll get some nice validation for free.
Introducing your own Data Annotation attribute for MVC2 is just a matter of creating a derived Class from ValidationAttribute and override the IsValid method. By default this will be a server-side validator. To change that into a client-side validator takes some effort. The main steps are:
- Create a new validator Class derived from the generic DataAnnotationsModelValidator<--your custom attribute Class goes in here—> Class.
- Register the validator and Custom attribute in global.asax.
- Write a custom JavaScript validation function.
For all the details I would recommend reading this excellent article about ASP.NET MVC 2 Custom validation.