How to Enable Client Side Validation in ASP.NET MVC 2
Last night I was teaching MVC framework as part of an ASP.NET course. One of the things that I showed the students was how to use data annotations for server side validation. I got a question about how to enable client side validation in MVC 2 and decided to write about it in a post. So here it goes…
MVC Server Side Validation
In MVC 1 we didn’t have client side validation out of the box. In order to achieve validation we needed to use one of two ways:
- Implement the IDataErrorInfo interface. In this way every model entity which needs validation have to implement that interface.
- Decorate every model entity with data annotations for validations. This is my preferred way since it is more elegant and you don’t need to hold the validation implementation inside your model entities.
These ways are server side validation. For client side validation we needed to use client side libraries such as jQuery Validator plug-in and write the client validation code. In MVC 2 this was made easier to implement.
Enabling Client Side Validation in MVC 2
Lets take a look at an entity which is decorated with data annotations:
As you can see the course require a title, its credit needs to be between 1 to 4 and the Days property has length of maximum 5 characters. In the courses controller I want to make validation so I hook up the server side validation like I was doing in MVC 1 in the controller:
The ModelState.IsValid property will trigger the validation on the entity and we will get server side validation. If we want to get client side validation we will have to activate it on the view. In MVC 2 we have another extension method on the HtmlHelper class that will help us to do so. The method is called EnableClientValidation. The create view will look like:
The place to link them is of course the master page so here is the master page implementation:
That is it. Now you have client side validation hooked in your MVC 2 web application.