Validating Data On Web Forms

alidating the information entered by users is an essential part of developing a professional Web-based user interface. Data validation over the Web is performed in one of two locations: on the user’s computer, or on the Web server.

There are six controls included with ASP.NET that simplify data validation.

Prior to ASP.NET, data validation was performed through scripts using either JavaScript or VBScript. Hence, many times validation was not performed in a uniform manner, complex validation was difficult to implement, and Web servers were vulnerable to validation scripts being modified by malicious users.

Most applications perform their data validation on the user’s local computer. In this scenario, if an error occurs while performing validation on the user’s computer, the application can directly display the error message on the page that the user is viewing without the page making a round trip to the Web server and then back to the user. This increases performance and reduces traffic over the Web.

A slightly negative aspect of validating data on the user’s computer is that the validation is performed via a script residing in the Web page. Thus, the validation script is browser-specific. You only have two possible scripting languages that you can use on a user’s computer: VBScript or JavaScript. Some resources also refer to Jscript (Microsoft) and ECMAScript (European Computer Manufacturer’s Association), but these are both derivatives of JavaScript. Since only Microsoft Internet Explorer supports VBScript, you’ll probably choose JavaScript as your primary scripting language to use on a user’s computer.

In addition, malicious users can subvert the validation process. Users with harmful intent may easily modify the validation script because it is contained in the source of the page that is sent to the user’s computer. The malicious user can then submit the modified script to the Web server with results that are different than what you, the developer, intended.

The alternative to processing data validation on the user’s computer is to process it on the Web server. The opposite pros and cons that applied to processing data validation on the user’s computer apply to processing data validation on the Web server. For instance, since the validation occurs on the Web server, your application must post the Web page that the user is viewing back to the Web server for validation to occur. This decreases performance since the page must make a round trip to the Web server and back to the user’s computer if data validation fails. However, when you validate a process on the Web server, you can use any scripting language because the user’s Web browser doesn’t process the scripting language. Furthermore, the data validation scripts are protected inside the Web server so they are not vulnerable to malicious user modifications.

RequiredFieldValidator Control
The most commonly used ASP.NET data validation control is the RequiredFieldValidator control. To use it, you link the RequiredFieldValidator control to another control, such as a textbox, and use it to determine if the linked control has a value entered into it or it is empty. If the linked control has a value entered into it, data validation will succeed. Alternatively, if the linked control is empty, data validation will fail.

You’ll mostly use RequiredFieldValidator controls in conjunction with textbox controls. In the snippet that follows I’ve indicated the HTML to generate both an asp:TextBox control and a linked asp:RequiredFieldValidator control.


In the snippet above I’ve declared a textbox with an ID attribute called txtName. The RequiredFieldValidator linked to it has an ID attribute called rfvName and I’ve included some of the most commonly used attributes. I used the ControlToValidate attribute to link RequiredFieldValidator to the textbox. The RunAt=”Server” attribute is required for all ASP.NET Web server controls.

The Display attribute determines how space is reserved to display the validation control message if data validation fails. The value of Static specifies that ASP.NET will allocate the space on the page when the page is rendered. Static is the default value. Other possible values for the Display attribute are Dynamic and None.

The HTML rendered by the ASP.NET validation controls uses a script library called WebUIValidation.js and implements Microsoft JScript functionality that is only supported by Microsoft Internet Explorer 4.0 and later versions.

A Display attribute value of Dynamic specifies that you don’t want ASP.NET to allocate any space on the page ahead of time to display a validation control message. If validation fails, ASP.NET will dynamically allocate space on the page on the fly. If you choose the Dynamic value and your validation fails, you could cause visual layout problems on pages that use HTML tables for page layout. If your validation control is contained inside of a table cell, the table cell will dynamically expand to accommodate the display of the validation error message.

When you choose to set Display=”None” this specifies that no error message will display for the validation control regardless of the outcome of the data validation process. The None value is useful when you use it in combination with the ValidationSummary control that I’ll illustrate later in this article. Figure 2 shows an excerpt from the sample page output from the HTML snippet shown above.

CompareValidator Control
Use the ASP.NET CompareValidator control to compare the value in a control to either a static value or to the value in another control. You link CompareValidator to a control in the same manner as the RequiredFieldValidator control (via the ControlToValidate attribute). The CompareValidator control performs pass or fail validation in the same manner as the RequiredFieldValidator control.

The HTML snippet below illustrates a TextBox control and a CompareValidator control where the validation control compares the value entered into the textbox against a static value that is stated in the validation control markup. As with the RequiredFieldValidator control, when you choose to enable validation on the user’s computer, the error message will display when your user navigates away from the textbox control if validation fails.


The snippet above creates a TextBox control linked to a CompareValidator control. You already know what some of the attributes are. The attributes shown above that I need to explain are: ValueToCompare, Operator, and Type.

Just as its name states, the ValueToCompare attribute specifies the static value to compare the value in the ControlToValidate control to. In the example snippet above, the value is a name (“Shannon”).

The RequiredFieldValidator control is the only data validation control that will fail the data validation process if the control that it is linked to contains no value.

The Operator attribute specifies the operator to use for comparison. The possible values for the Operator attribute are: DataTypeCheck, Equal, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and NotEqual. The name of each should be self-explanatory as to what comparison will be made. The DataTypeCheck value will determine if the values are of the same data type.

The Type attribute specifies the data type of the comparison to be made. The possible values for the Type attribute are: Currency, Date, Double, Integer, and String. For an excerpt from the generated page, see Figure 3.

RangeValidator Control
A developer uses the ASP.NET RangeValidator control to determine if the value entered into a control is included within a specified range of values. The RangeValidator control uses most of the attributes that I’ve illustrated above in the other validation controls.

The HTML snippet below declares a TextBox control to collect a user’s age. The snippet shows how to use the rvAge RangeValidator control to determine if the age entered is within a pre-determined range.


The snippet above declares the range for the RangeValidator control using the MaximumValue attribute and the MinimumValue attribute. The Type attribute specifies that you want to compare only an integer data. See the sample validation in action in Figure 4.

RegularExpressionValidator Control
You can compare the value entered into a control against a regular expression if you use the ASP.NET RegularExpressionValidator control. A regular expression is a series of characters that define a format expression that you can apply to a value. An overview of regular expressions is beyond the scope of this article. However, you can read about the fundamentals of regular expressions in “Getting Started with Regular Expressions” in the May/June 2003 issue of CoDe Magazine. You can also find a detailed discussion of regular expressions in the Visual Studio .NET Help file as well as in the MSDN library.

In this HTML snippet, the value entered into a textbox control is compared to a regular expression that was created to validate an e-mail address format.


In the snippet above, I’ve linked the RegularExpressionValidator control to the txtEmail TextBox control using the ControlToValidate attribute. By now, the only attribute that isn’t immediately obvious to you is the ValidationExpression attribute.

The ValidationExpression attribute defines the regular expression used to compare the value in the control to. You can see the results of the RegularExpressionValidtator control in Figure 5.

CustomValidator Control
To perform custom validation beyond that already provided by the other ASP.NET validation controls, the CustomValidator control processes a custom script that must return true or false to indicate success or failure of the validation process.

ASP.NET processes all validation controls on the server and, optionally, on the user’s computer. You must write a custom function member for the CustomValidator to process on the Web server. You may also write a script for the CustomValidator to process on the user’s computer.

In the HTML snippet below, a CustomValidator validates the value entered into a TextBox control to determine if the value is a prime number.


Here I’ve specified the txtPrimeNumber TextBox control as the control to validate using the ControlToValidate attribute of the CustomValidator control. I want the CustomValidator control to process two scripts: ClientValidation and ServerValidate, which I specify using the ClientValidationFunction attribute and the OnServerValidate attribute, respectively.

The ClientValidationFunction attribute designates the validation script that the CustomValidator control will process if the EnableClientScript attribute has a value of true. The function name you specify in your validation script must match the value you specified in the ClientValidationFunction attribute. I wrote the validation script in this example using JavaScript.


When the CustomValidator calls the ClientValidationFunction, it passes a reference to the calling object as well as the attributes associated with the calling object. The Value property of the txtPrimeNumber TextBox control as well as the IsValid property are accessed through the arguments parameter that is passed.

The OnServerValidate attribute identifies the function member to process on the Web server for data validation. This function member can carry out a completely different process than the ClientValidationFunction. However, in most cases, the function member on the Web server and the script on the user’s computer are identical in functionality. Here I’ve used C# to write the ServerValidate function member used in this example.

   protected void ServerValidate(object sender,         ServerValidateEventArgs e)   {      int primeNumber = int.Parse(e.Value);      for (int counter = 2;         counter <= (primeNumber/2);         counter++)      {         if ((primeNumber % counter) == 0)         {            e.IsValid = false;            return;         }      else         {            e.IsValid = true;            return;         }      }   }

The function member shown above is identical in functionality to the validation script I wrote in JavaScript. Figure 6 shows the CustomValidator control in action.

ValidationSummary Control
The ASP.NET ValidationSummary control differs from the other validation controls in that it does not perform data validation directly. Instead, the ValidationSummary control displays a summary list of error messages from any of the validation controls on the current Web form that fail data validation. You don't need to link the ValidationSummary control to the other Web controls or validation controls on the page. In the HTML snippet below, I declare a ValidationSummary control with many of the most commonly specified attributes shown.


The snippet above features several new attributes. The DisplayMode attribute determines the format of the summary list that the ValidationSummary control will display. The possible values for the DisplayMode attribute are BulletList, List, and SingleParagraph. The BulletList value displays each data validation failure as a separate bullet item in a bulleted list. The List value displays each data validation failure as a separate line item in a non-bulleted list. The SingleParagraph value displays each data validation failure as a separate sentence delimited by periods in a single paragraph format.

The ShowMessageBox attribute determines whether you want a message box to pop up in the user's browser that displays the data validation failure items. The possible values for the ShowMessageBox attribute are true and false. The ShowSummary attribute determines whether you want a summary of the data validation failure items to display on the current Web form at the location where you've declared the ValidationSummary control. The possible values for the ShowSummary attribute are true and false.

The HeaderText attribute defines an optional line of header information that you can display above the list of data validation failure items. In both the popup message box and the on page summary, the header line will display just above the items summary.

Figure 7 shows an excerpt from the sample page where I show the ValidationSummary control in all three of the DisplayMode states. Figure 8 shows the popup message box that the ValidationSummary control displays.

Manually Enabling Validation Controls
The sample page for this article illustrates several examples of ASP.NET validation controls. Two of the validation controls on the page are accompanied by button controls that cause the page to be posted back to the Web server. When you're faced with multiple points on the page that can cause a post back on a Web form, managing validation controls can be tricky. It may be necessary to manage data validation controls on Web forms that have multiple separate sections displayed on them where each section can be posted back to the Web server, or submitted, separately.

For example, I've divided my sample page into several sections with each section illustrating a different data validation control. When a user clicks the first button control, if there is no data entered into the textbox control that is linked to the RequiredFieldValidator control, then the RequiredFieldValidator control returns false, displays its error message, and prevents the user from posting the page back to the Web server. You expect this behavior of the RequiredFieldValidator control, right? Here's the catch: the RequiredFieldValidator will behave in this manner regardless of where the page is posted back to the Web server from. Thus, if a user clicks the second button control, even though it is at a different point in the page, the RequiredFieldValidator at the top of the page will prevent the page from being posted back to the Web server.

The scenario above represents just a single example where it would be helpful to be able to manually and conditionally enable and disable the ASP.NET data validation controls. You can easily disable validation controls by simply setting the Enabled property of any of the validation controls to false. But, disabled validation controls will not perform data validation. However, validation controls that you've disabled can be enabled at any point that you need their services.

If you need to manage when data validation controls are enabled, a quick solution is to simply disable them by default. In the server-side function member that will be processed by the event that causes the page to be posted back to the Web server, you can take steps to validate the information that was submitted.

You first want to re-enable the needed validation controls. Next, call the Page.Validate function member provided by ASP.NET. This function member causes all of the validation controls on the Web form to validate the information submitted to the Web server. Finally, check the state of the Page.IsValid property. If any of the validation controls on the Web form were unsuccessful in the validation process, the Page.IsValid property will contain a value of false. The steps mentioned here give the developer complete manual and conditional control over when you want to enable the data validation controls. The snippet below illustrates the steps mentioned here.

   public void SomeEventHandler()   {      rfvSample1.Enabled = true;      Page.Validate();      if (Page.IsValid)      {         // Take some action based upon all data         being valid.      }      else      {         // Take some other action based upon some          some data being invalid.      }

You can also manually and conditionally control data validation when you're performing client-side validation by simply having the script that performs the validation return a true or false. However, taking manual control over when validation occurs on the user's computer isn't common since the Web server will always process the validation controls.

Combining Validation Controls
Note that the RequiredFieldValidator control is the only data validation control that will fail the data validation process if the control that it is linked to contains no value. The CompareValidator, RangeValidator, RegularExpressionValidator, and CustomValidator will all pass validation if the value contained in the linked control is a valid value as well as if there is no value in the linked control. For this reason, you may need to combine multiple validation controls and link them to the same target control to be validated.

The validation controls are not actually combined in any way, but you can link multiple validation controls to the same target control to validate that target. In this manner, you can link both the RequiredFieldValidator control and one of the other validation controls, such as a RangeValidator control, to a TextBox control so that the TextBox must have a value entered in order to pass validation.

Validating the data entered by users is a vital part of any software application. Data validation processing prevents wasting time processing invalid data and guards the integrity of a data store by only allowing valid data to be entered into an application. Microsoft's ASP.NET data validation controls do a superb job standardizing the means of validating data entered by a user over the Web.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles:

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.