Using Unobtrusive Validation in ASP.NET 4.5 Web Forms

Originally published June 21, 2012.  Last updated May 17, 2013.

Introduction

ASP.NET Web Forms have provided validation controls since the initial releases. In the earlier releases of ASP.NET these validation controls used JavaScript emitted by ASP.NET Web Form framework. The unobtrusive validation, however, makes use of the data-* attributes of HTML5 for validation purpose. This article shows how the new unobtrusive validation features work for Web Forms.

What is Unobtrusive Validation?

Prior to ASP.NET 4.5 validation controls used to automatically emit JavaScript code for performing client side validations. Consider the following figure that shows the JavaScript code generated for a sample web form.


JavaScript code generated for a sample Web Form

As you can see there is lot of JavaScript code being emitted under this scheme. If you use unobtrusive validation, Web Forms page framework emits data-* attributes of HTML5 that contain the validation information. The following figure shows how these data-* attributes look:


Data-* attributes

As you can see a <span> element holds data-* attributes that contain validation message and other information. There is no JavaScript generated. This approach reduces page size to a great extent. Additionally unobtrusive validation relies on the jQuery library rather than some proprietary script. ASP.NET MVC already uses unobtrusive validation and now Web Forms also support them. 

Enabling Unobtrusive Validation in ASP.NET Web Forms

If you create a new Web Forms project, the unobtrusive validation is enabled by default. If you open the web.config of a newly created Web Forms project you will find the following markup in the <appSettings> section:

<appSettings>
  <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />
</appSettings>

The ValidationSettings:UnobtrusiveValidationMode key determines the UnobtrusiveValidationMode for the entire application. The possible values are None and WebForms. The value of None indicates that unobtrusive validation is disabled whereas a value of WebForms means it is enabled.

You can also set the unobtrusive validation mode in the Global.asax file or in the individual Web Form. To set the unobtrusive validation mode in the Global.asax file you set the UnobtrusiveValidationMode property of ValidationSettings object in the Application_Start event.

protected void Application_Start(object sender, EventArgs e)
{
   ...
   ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.WebForms;
}

If you wish to set the unobtrusive validation mode at individual web form level you set the UnobtrusiveValidationMode property of the Page object in the Page_Load event handler.

protected void Page_Load(object sender, EventArgs e)
{
   ...
   Page.UnobtrusiveValidationMode = UnobtrusiveValidationMode.WebForms;
   ...
}

Adding Script Resource Mapping for jQuery library

Enabling the unobtrusive validation is one part of the story, you also need to register jQuery library with ScriptManager class. This step is required because unobtrusive validation relies on jQuery library for its functioning. To register the jQuery library with ScriptManager you need to add the following code in the Application_Start event handler:

protected void Application_Start(object sender, EventArgs e)
{
    ScriptResourceDefinition jQuery = new ScriptResourceDefinition();
    jQuery.Path = "~/scripts/jquery-1.7.2.min.js";
    jQuery.DebugPath = "~/scripts/jquery-1.7.2.js";
    jQuery.CdnPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.7.2.min.js";
    jQuery.CdnDebugPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.7.2.js";
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", jQuery); 
    ...
}

The above code creates an instance of ScriptResourceDefinition class. The ScriptResourceDefinition essentially provides path information for a script. Notice that the above code sets four paths, viz. Path, DebugPath, CdnPath and CdnDebugPath. The purpose of these properties is as follows:

  • Path :  Specifies the release mode path of a script file.
  • DebugPath : Specifies the path of a script file to be used when debug mode is enabled.
  • CdnPath : Specifies the release mode path of a script file from a Content Delivery Network (CDN).
  • CdnDebugPath : Specifies the path of a script file from a Content Delivery Network (CDN) when debug mode is enabled.

In the above example, the jQuery file resides in the Scripts folder and Microsoft AJAX CDN is used as a CDN. Make sure to change the paths as per your setup.

Once the ScriptResourceDefinition instance is ready, you add this definition to the ScriptResourceMapping using AddDefinition() method. The first parameter of the AddDefinition() method is the name of the script resource and it must be jquery for jQuery library. The second parameter is a ScriptResourceDefinition object.

Testing Unobtrusive Validation

Ok. That's all you need to do for enabling unobtrusive validation. To test the unobtrusive validation you can create a sample web form that uses validation controls. The following figure shows a simple data entry form for the Customers table of Northwind database. The web form consists of a FormView control. The InsertItemTemplate of the FormView is shown below:


InsertItemTemplate

The form uses RequiredFieldValidator controls for all the fields, viz. CustomerID, CompanyName, ContactName and Country. The error messages are displayed in a ValidationSummary control. The Web Form also enforces server side validations using data annotations. These server side validation errors are displayed after a post back in the validation summary control. Complete source code of this test application is available for download along with this article.

Summary

Unobtrusive validation makes use of jQuery library and data-* attributes of HTML5 to validate data entered in the web form controls. Unobtrusive validations can be enabled in the web.config file, Global.asax or individual Web Form code-behind. Using unobtrusive validations reduces the response size because no JavaScript is emitted by the page framework. The usage of validation controls remain the same irrespective of whether you use unobtrusive validations or not.



Related Articles

Downloads

Comments

  • Database query

    Posted by Sample Forms on 07/19/2013 12:25am

    Thanks for the article can i use forms authentication with SQL server database?

    Reply
  • Cheap Oakley Hijinx free shipping

    Posted by ivcscimry on 06/20/2013 10:30pm

    Cheap oAkLeys ,Like a sports brand, fashion, sports Oakley sunglasses dominant position inside international arena, streamlined shape synonymous with beautiful. These sunglasses in the different lens color and tone, almost each last style has become produced by expert designers to make the wearer each side fashion, taste and fashion. Replica Oakley Sunglasses ,Oakley sunglasses is going to be impressive, and in addition to a clear overall appearance became run usually means that this person you selected an internet business as a new rather wind. Oakley is often a trend, and provides real-world imitate two glasses of sunglasses models, it's a well-known optical company Bausch & Lomb Bausch & Lomb brand. cheap Oakley HIjInx ,Those defending the clothing colors will have to protect yourself, and sometimes terrible events, considering that the situation is a lot like sunlight: unique. Why Oakley could turned into a professional some of the athletes preferred choice, the brand is the primary objective in the cutting edge of this marketplace currently wearer Kun pounds copy in the safety and eye safety. I don't think what professional athlete refused Oakley products bring high-definition and open peripheral vision. In mid-summer day, UV radiation could be up to threefold more in the winter months. Above all, the extent of UV trigger is basically the greatest harm, ultraviolet light, will be approximately 10-fold increase. And there is a large number of kinds of glasses, you will be certain to be described as a little thing, and refers to any person's spouse and youngsters. Product design or selection of materials, has become a compilation of advanced scientific experiments and testing to guarantee the comfort and high-quality, high level of integration and functionality and fashion. Such a professional sports mirror which has a unique personality, the full range of functionality to win the respect of countless celebrities around the globe. Actually your discerning noted that this unique tone of Oakley, Oakley colors means that you can take notice of the product inside time. Most girls tend to be like the development sari, linked to the safety of this style are conscious of a brandname image along with Oakley sunglasses cheap teenager understand that this manufacturer. Fortunately, Oakley sunglasses have different prices to satisfy their quality, but less difficult than trawling round shops to buy online suppliers.

    Reply
  • ASP.NET Validation

    Posted by Andrew on 05/30/2013 03:59am

    Hi, This is very informative article. Thanks for sharing your knowledge. There are few links that also helpful for developers. http://mindstick.com/Articles/cb1ae170-021f-4fd0-bb53-2225744bb89f/?Regular Expression in ASP NET http://mindstick.com/Articles/c3825daa-a449-467d-9513-34a8232d498a/?Validations on Asp Net Control http://msdn.microsoft.com/en-us/library/ms972961.aspx http://msdn.microsoft.com/en-us/library/aa479013.aspx

    Reply
  • Nike Zephyr Max 1 FB liberating, father a fervent color texture, the chic shoes

    Posted by Geozyoceada on 04/23/2013 12:34am

    In the summer in a glass interior the cool sprite seems to be a decorous creme de la creme, but if the sprite "feet"? Will also supply you a lapse, take a slaking nourishment! This summer, Nike and Sprite [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] and his sneakers to a blend of outstanding example snow spread of callow, drained and downcast color schematic in the undying Nike Superciliousness Max 1 shoes romp a like a breath of fresh air presumptuous scent.[url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] Summer is the metre to select a cleanly shoe, shoes should be a acceptable choice. Qualifying series Nike Quality Max HomeTurf megalopolis recently finally comes up, this series in the immortal Freshen Max shoes to London, Paris and Milan the three paid glorification to the iconic megalopolis of Europe, combined with the characteristics of the three cities, Sense Max 1 HYP,Air Max 90 HYP,Connected Max 1 and shoes such as Air Max 95, combined [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] with the Hyperfuse, as well as a heterogeneity of materials, such as suede, Whether you after functional or retro-everything.

    Reply
  • worked

    Posted by Tom on 01/03/2013 02:45am

    Great, it really worked for me, after trying all other similar tutorials which were not working

    Reply
  • Web- / System-developer

    Posted by Marcus Andersson on 08/17/2012 02:03am

    Great article! I have one question though (hopefully not a stupid one...): - What happens if the user enters the page using a web browser that can't deal with HTML5 data-attributes? Is there a fallback?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: March 27, 2014 Teams need to deliver quality software faster and need integrated agile planning, task tracking, source control, auto deploy with continuous builds and a configurable process to adapt to the way you work. Rational Team Concert and DevOps Services (JazzHub) have everything you need to build great software, integrated seamlessly together right out of the box or available immediately in the cloud. And with the Rational Team Concert Client, you can connect your …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds