Using Unobtrusive Validation in ASP.NET 4.5 Web Forms

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


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:

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

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 = "";
    jQuery.CdnDebugPath = "";
    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:


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.


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



  • Well written article

    Posted by goodsammy on 01/04/2016 10:39am

    I needed help with Unobtrusive Validation and did not find many articles which explained it this clearly. Thank you very much.

  • UnobstrusiveMode

    Posted by mukunda saini on 09/17/2015 09:00am

    Thanks for the artical. It is very useful to developers..

  • Problem with display

    Posted by Arulmani on 08/31/2015 04:37pm

    Hi, Thanks for your post.. I'm using telerik Ajax control, when i add Unobtrusive Validation in web.config file, while using required field validation text box size reduced to small size.... Help me with this issue Thanks, Arulmani.A

  • About Article

    Posted by Punam on 08/06/2014 06:14am

    Thanks for this article!!! I searched a lot but not getting what i want...but after reading this article i got what i'm searching...

  • 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?

  • 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.

  • 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. Expression in ASP NET on Asp Net Control

  • 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=]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=]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=]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.

  • 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

  • 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?

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

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date