RSS

MVC Validation – Part 3 – Client-Side Validation

04 Jul

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:

ClientValidationEnabled Key

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.

Validation summary declaration

Step 3 – Jquery & Unobstrusive Javascript

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)

MVC 3 uses JQuery and unobtrusive javascript to provide valdiation (unlike MVC 2) and when constructing the markup. Ensure that these 2 script files are referenced either on your page or in the _Layout.cshtml if you
are using a ‘master’ page.

Also add the following key to the appsettings node in the web.config to ensure we are using unobtrusive javascript:

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.

MVC 2 used JSON to enforce client-side validation

However as MVC 3 uses Unobtrusive Javascript, the JSON has been replaced with HTML 5 compatible tags which make for much cleaner code e.g.

MVC 3 uses unobtrusive javascript

You can try this for yourself by just setting the UnobtrusiveJavaScriptEnabled key true & false

Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: