- MVC Validation – Part 1 – Model Data Annotations
- MVC Validation – Part 2 – Custom Validation
- MVC Validation – Part 4 – Styling the Validation Controls
A great feature about MVC 3 is the ability to swap between Server and Client side validation, easily and painlessly.
In Part 1 and 2, I created a simple Customer Creation form and applied standard and custom validation to the model class. However, when we run the application you might have noticed a ‘post back’ prior to the validation summary being displayed. This is because, by default, MVC 3 applies Server-Side validation.
In this article I will switch our Customer creation example to use Client-Side Validation instead.
Step 1 – Turning on Client Side Validation
By default, server-side validation is enabled but we have the ability to change this to client-side on a page-by-page basis or for our whole application.
To turn on Client-Validation for the whole application, open the web.config and add the following key to the appSettings node:
Note: if I wanted only our Create.cshtml page use client-side validation then I can simply add the EnableClientValidation method to the page e.g.
Step 2 – Validation Summary
If you followed Part 1 then you would have allowed Visual Studio to create a view (Create.cshtml). In this case the ValidationSummary would have been automatically added.
If not ensure to have the ValidationSummary method call after the BeginForm statement e.g.
In our example you may have noticed these 2 script references at the top of our create.cshtml page (these are also shown in the screen shot above)
are using a ‘master’ page.
Its worth mentioning, just for your reference, that MVC 2 used JSON to enforce the validation in the markup once the page was rendered e.g.