Home > ASP.NET MVC, CSharp, JavaScript, jQuery > ASP.NET MVC 3: Unobtrusive Client Side Validation

ASP.NET MVC 3: Unobtrusive Client Side Validation

In this post we will look at one of the new features of the fresh new release of ASP.NET MVC 3 – using unobtrusive client side validation through the new HTML5 data-* attributes. I will show what these attributes look like and how they come into play.

Client Validation by Default

One of the main differences between the new version and the previous two MVC 1 and MVC 2 is that client side validation is turned on by default. This is done using an AppSetting in the web.config file:

<appSettings>
  <add key="ClientValidationEnabled" value="true"/>
</appSettings> 

If you remember up until ASP.NET MVC 3 you had to explicitly specify that you want client side validation to be performed like this in your view:

<% Html.EnableClientValidation(); %>

If you don’t want any validation in the browser you could turn it off by changing the AppSetting value of ClientValidationEnabled to false.

Unobtrusive Validation

Validation in ASP.NET MVC is based on meta data provided by DataAnnotations. There are quite a few classes that are really handy in describing what rules your properties must obey and the framework will take care of the rest. The HTML Helper classes (Html.TextBoxFor, Html.EditorFor, etc.) used to render different HTML controls look up these meta data attributes when the response is being generated and render the appropriate output so that validation can occur on the client’s browser.

By taking advantage of Unobtrusive JavaScript you don’t clatter your HTML markup with unnecessary JavaScript event handlers and so on. The HTML elements describe themselves through attributes and you get a HTML5 ready markup by default. Here is a sample UserModel class that I will use in a create user form annotated with validation attributes:

public class UserModel
{
    [Required]
    [StringLength(50)]
    public string Username { get; set; }

    [Required]
    public string Password { get; set; }

    [Required]
    [Compare("Password")]
    public string ConfirmPassword { get; set; }

    [Required]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required]
    [StringLength(50)]
    [RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$")]
    public string Email { get; set; }
}

When the user tries to submit the form with invalid data he/she will see the following messages:

Unobtrusive Client Side Validation

If we look at the confirm password input element for example we will see the following HTML markup:

<div class="editor-field">
    <input type="password" name="ConfirmPassword" id="ConfirmPassword" data-val-required="The ConfirmPassword field is required." data-val-equalto-other="*.Password" data-val-equalto="&amp;#39;ConfirmPassword&amp;#39; and &amp;#39;Password&amp;#39; do not match." data-val="true">
    <span data-valmsg-replace="true" data-valmsg-for="ConfirmPassword" class="field-validation-valid"></span>
</div>

As you can see there are a few data-val* attributes that add meta data to both this field and the span element that shows validation messages. Behind the scenes ASP.NET MVC uses jQuery Validation plugin and the Unobtrusive validation support library for jQuery Validate written by Microsoft. If you however decide to turn unobtrusive validation off your HTML markup won’t include the new HTML5 data-* attributes but a JavaScript code that will set up the Validation plugin.

For the ConfirmPassword property I have used one new attribute that comes with this new release part of .NET Framework 4.0 – CompareAttribute. It gives you the ability to compare two properties of a model.

Summary

As you can see ASP.NET MVC 3 is not lagging behind the current trends in web development utilizing some of the new HTML5 features and unobtrusive JavaScript. What I like about ASP.NET MVC and DataAnnotations is that we as developers don’t need to focus and waste too much time on simple validations like required fields, maximum length, etc. and focus on the business logic and any business rules that need to be enforced.

About these ads
  1. muruga
    February 28, 2012 at 12:54 pm

    Hi,it’s great but use guys are tool general html syntax in view.
    but i want to use razor syntax can u plz help me on that one.

    thanks in advance.

  2. muruga
    February 28, 2012 at 12:54 pm

    muruga :
    Hi,it’s great but u guys are tool general html syntax in view.
    but i want to use razor syntax can u plz help me on that one.
    thanks in advance.

  3. April 1, 2012 at 9:47 am

    Hi,
    Nice approach, you explained very well about validation in ASP.NET MVC3. I am a new learner in ASP.NET MVC3 and this article is great helpful for me. I learned about validation and I compare it from ASP.NET then I found that it is very easy to implement it in MVC. We can implement it in one place and it react in both place which is server side and client side. It’s really good to know it. I had explained few basic things about validation in ASP.NET MVC3 using razor view engine at following url

    http://dabbu-csharphelp.blogspot.in/2012/01/validation-in-asp.html

    I think this is useful for beginners who wnt to know basic of validation in ASP.NET MVC3. Thanks for sharing such a useful articlde on validation.

    Thanks.

  4. Atul
    June 26, 2013 at 7:03 pm

    first time the validation is not working on focus out and keydown. do we need any setting for this

  1. June 6, 2011 at 9:55 pm
  2. January 21, 2013 at 1:09 am

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: