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.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read