One essential task in Web programming is the validation of values entered into forms by users. Classic ASP provides little support in this area, leaving developers to devise their own validation mechanisms. Luckily, ASP.NET has improved this situation considerably. For starters, its event-based, UI control-centric WebForms programming model greatly simplifies the task of implementing your own validation. But ASP.NET goes even further, providing direct support for validation through a set of server controls that all but eliminate the need to implement your own validations. In this article, I’ll introduce and demonstrate the validation server controls shipped with ASP.NET.

Validation control hierarchy
The ASP.NET validation server controls live under the System.Web.UI.WebControls namespace, together with Web sever controls such as TextBox and Label. ASP.NET provides six concrete validation controls, shown in green in Figure A.

Figure A
ASP.NET validation controls

The ValidationSummary control doesn’t actually perform validation. Instead, it provides a way to summarize the error messages from the other validation controls within the page. For the remainder of the article, when I refer to validation controls, I’m referring to those controls that actually perform validations—all of the validation controls except ValidationSummary.

Validation controls are derived directly or indirectly from the abstract BaseValidater class, which in turn derives from the Label control. At first, it seems odd that validation controls would derive from Label, but we’ll see why shortly.

A validation control works by evaluating the value of an input server control on the page to see whether it meets certain criteria. The input control to evaluate is specified through the validation control’s ControlToValidate attribute. You can programmatically cause a validation control to perform its evaluation by calling its Validate method, which sets the validation control’s IsValid property to true if validation succeeds and false if it fails. You can cause all of the validation controls on a page to validate their input controls by calling the Page.Validate method.

The Page.IsValid property is set to true if validation succeeds for all validation controls within the page; otherwise, it’s false. The Page.Validate method is automatically invoked when a button control whose CausesValidation property is set to true is clicked. CausesValidation is set to false by default for a reset or clear button. The button click event is suppressed if IsValid is false for any validation control on the page.

If the target browser supports ECMAScript 1.2 (JScript) and a Document Object Model (DOM) compatible with Internet Explorer 4 or later, validation controls render client-side scripting to perform validation on the client without a round trip to the server. This provides more timely feedback to the user. To support downlevel browsers and to guard against a user attempting to bypass validation, validation is still performed on the server when the page is posted to it. Client-side validation can be disabled for a validation control by setting its EnableClientScript property to false. You can disable client-side validation for all validation controls within the page by specifying the attribute ClientTarget=”downlevel” in the @Page directive.

When validation fails, the Text property of the validation control is displayed in-line within the page at the validation control’s location, just like a label. If the Text property is not set, the ErrorMessage property is displayed instead. The ErrorMessage property is also displayed in the ValidationSummary control when validation fails. Nothing is displayed in the ValidationSummary if no ErrorMessage is set for a validation control. One strategy involves setting a brief message or error indicator as the Text property and a longer explanation as the ErrorMessage property.

Different validation controls test different criteria:

  • ·        RequiredFieldValidator—Validation succeeds if any value has been entered in the input control.
  • ·        RangeValidator—Validation succeeds if the input control’s value falls within the range specified by the MaximumValue and MinimumValue properties. The Type property specifies the data type to which MaximumValue, MinimumValue, and the input control’s value are converted before performing the range comparison.
  • ·        RegularExpressionValidator—Validation succeeds if the input control’s value matches the regular expression specified in the ValidationExpression property.
  • ·        CompareValidator—This control can perform several types of evaluation through its Operator property. The DataTypeCheck operator simply determines whether the input control’s value can be converted to a data type specified by the Type property. Relational operators, such as Equal or GreaterThan, compare the input control’s value with either a static value, specified by the ValueToCompare property, or with the value of another control, specified by the ControlToCompare property.
  • ·        CustomValidator—This control enables you to perform your own unique validation by handling the CustomValidator.ServerValidate event, fired when CustomValidator.Validate is called. The event handler can evaluate whatever you want and set the IsValid property of the ServerValidateEventArgs event argument to set the state of the validation control. A ServerValidate event handler can be specified through the OnServerValidate property. Specifying a client-side script function through the ClientValidationFunction property enables client-side validation.

Validation in action
Listing A shows NewBabyBoomer.aspx. This is a sign-up page to create a new account at an imaginary Web site providing information to members of the baby boom generation, those born between 1946 and 1964. This page is typical of many sign-up pages. The user is asked to choose a username and a password and to enter the password again as confirmation. The page also asks the user to enter the year in which he or she was born.

The Label, TextBox input control and validation controls for each field are arranged within a Web server Table control. The Table control is followed by a button control and a ValidationSummary control. Button_Click, the OnClick event handler for the button control, is contained in a <script> block at the top of the aspx file. Figure B shows the initial NewBabyBoomer page.

Figure B
Baby boomer sign-up page

All fields in the NewBabyBoomer page are required. As a result, each input control is validated by two validation controls. A RequiredFieldValidator ensures that some value is entered in the input control. A second validation control then evaluates the value.

If you’re dealing with optional fields, you can use validation controls, such as RegularExpressionValidator, CompareValidator, and RangeValidator. With those controls, validation succeeds if the target input control has no value, so you can make a field optional but still apply validation when the user chooses to enter value.

In NewBabyBoomer, a RegularExpressionValidator validates the Username field to ensure that the username is at least six alphanumeric characters long. The regular expression “\w{6,}” is specified through the ValidationExpression property. A RegularExpressionValidator likewise validates the Password field, though the ValidationExpression is set to “.{6,}” to allow the password to contain any character, so long as the length is at least six characters.

A RangeValidator validates the Year Born field to ensure that the input control’s value is an integer within the range 1946 to 1964. Validation fails if the value falls outside the range or if the value is not convertible to an integer. Finally, a CompareValidator specifying the Equal operator validates the Confirm field to ensure that it matches the Password field.

Figure C shows the output of the validation controls and the ValidationSummary control when invalid input is entered. The Button_Click event handler is called when the Create Account button is clicked and all fields are valid. The Page.IsValid property is checked within the event handler in case the page was posted back from a downlevel browser. Figure D shows the confirmation page after a successful account creation.

Figure C
Validation control output

Figure D
Validation confirmation

The new validation controls available in ASP.NET provide the necessary functionality for any Web development effort. This is a great improvement over the basic ASP technology. I hope this article has provided the groundwork for employing the validation controls in your next development project.