Introduction
ASP.NET 2.0 offers a wide variety of ways to capture user input. This translates to, many opportunities for users to provide bad data. In this article, you will learn about the support that ASP.NET provides to you for performing data validation.
Validating Data
Often, bad data doesn't affect your organization until someone tries to report against it or some business intelligence project uncovers the presence of inconsistencies. If bad data is discovered in these circumstances, correcting it is an overwhelming, if not impossible, task. There could be millions of records with inconsistent and erroneous information. All these instances will skew your reports and make your business intelligence efforts more ambiguous.
So that you can avoid correcting bad data, you must validate data at the time of entry and, thereby, prevent bad data from getting into your systems. ASP.NET 2.0 provides some excellent support for performing data validation. In this article, you will see, choosing an appropriate data validation technique and then how to implement that technique using the intrinsic ASP.NET 2.0 data validation controls.
Appropriate Data Validation Technique
In a multi-tier architecture, the input source is not restricted to the UI and presentation layers. Data can come from many different sources such as other internal systems, other external systems, and other components of the same system. In this situation, it is not sufficient to rely solely on the presentation layer for validation.
On the other hand, if your application receives its input exclusively from the UI, then you can rely solely on the UI to validate the input data. In this article, we will mainly focus on validating data provided via a Web-based UI.
Validation Controls Common Properties
It should be no surprise that ASP.NET provides a solid base of validation controls. You can use these flexible controls out of the box or build on them through inheritance to create your own validation controls.
All ASP.NET validation controls have some common properties with which you should be familiar. The following listing describes the common properties among validation controls.
ControlToValidate: This property is used to indicate which control the validation control is to validate.
Display: This property provides three possible values. Setting the property to None prevents the control from being displayed inline. Use this setting in conjunction with the ValidationSummary control. The Static setting renders the validation control inline with other controls. This means that blank space is occupied by the control when it is not showing a message. Use the Dynamic setting when you want to avoid the control occupying blank space.
EnableClientScript: Not every browser supports JavaScript, and even browsers supporting it might have it disabled. However, for those browsers that support JavaScript, the validation controls can perform client-side validation as well as server-side validation. Client-side validation does not require a postback for validation to occur, resulting in a richer user experience. Note that client-side validation should be used only to provide a richer user experience and not as a replacement for server-side validation.
Enabled: This property determines whether the validation control actually performs validation.
ErrorMessage: This property is generally associated with the ValidationSummary control.
ForeColor: Use this property to set the color of the inline error message when validation fails.
IsValid: This property is used to evaluate whether validation fails.
SetFocusOnError: Setting this property to True causes the focus to be set to the control identified in the ControlToValidate property if validation fails.
Text: The Enabled property determines whether the validation control actually performs validation. The Text property is generally associated with the inline message–the message displayed at the location of the validation control.
ValidationGroup: Validation groups are new to .NET 2.0. This property is used to associate the current validation control with a specific validation group.
Now that you have been introduced to the common attributes of validation controls, you can dig deeper into specific facets of each validation control. You can use validation controls in combination. For example, you can use RequiredFieldValidator and RegularExpressionValidator controls on the TextBox control for capturing an e-mail address.
Validation Controls
RequiredFieldValidator Control: The RequiredFieldValidator control is used to ensure that fields that must be populated with data are, indeed, populated with data. This control can be used with virtually any data entry controls, such as TextBox, DropDownList, and CheckBox. The RequiredFieldValidator control works by comparing the selected value of the control specified in the ControlToValidate property against an initial value that you specify. If you do not specify an initial value, an empty string is assumed.
This initial value against which comparisons are made is established using the InitialValue property. The default value is an empty string. However, you can set it to any value you like. Suppose, for example, you want to provide some assistance to users specifying dates by pre-filling the date field with MM/DD/YYYY. In this situation, you can set the InitialValue property of the associated RequiredFieldValidator control. This means that the user is still required to specify a value and cannot rely on the initial default value that you provide for guidance.
RangeValidator Control: Situations in which a value must fall within a certain range, rather than merely being specified, call for the RangeValidator control. This control allows you to ensure that a specified value is within acceptable limits, using a combination of properties including MaximumValue and MinimumValue. If either of these properties is blank, the control assumes no maximum or minimum (depending on which is blank).
The RangeValidator control allows you to validate the ranges of various data types. You are not restricted to numeric types. In fact, the RangeValidator control supports range validation of any data type described by the ValidationDataType enumeration. These include Currency, Date, Double, Integer, and String.
RegularExpressionValidator Control: Regular expressions are an extremely powerful means of quickly parsing text. Regular expressions use an extensive pattern-matching notation to provide searching, replacing, and other text operations quickly and efficiently. The pattern-matching capabilities of regular expressions are of particular interest when using the RegularExpressionValidator control.
Regular-expression validation is generally used to ensure that specified data matches a predetermined pattern. For example, all e-mail addresses follow a common pattern. The regular expression used for comparison is specified with the ValidationExpression property. This property can contain any valid regular expression. Relying once again on the example of validating an e-mail address, you can use the following regular expression.
\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
It is pretty obvious that the regular expression syntax is quite cryptic. Fortunately, there are libraries of regular expressions available. In fact, the RegularExpressionValidator control has some predefined regular expressions (including e-mail address). You can always, of course, write your own regular expressions for validation. Suppose, for example, you have a custom purchase order number format. You can use a regular expression to validate data in the purchase order number field against the pattern you define.
CompareValidator Control: Sometimes you need to compare the value in one field to that of another field instead of to some preset value, range, or pattern. In these situations, you can use the CompareValidator control. Like other validation controls, this control uses a ControlToValidate property. In addition, it adds a ControlToCompare property. This property gives you the ability to specify another control against which the value of the control in the ControlToValidate property is compared.
If you want to compare the control's value against a constant value, you can use the ValueToCompare property instead of the ControlToCompare property. If you set both properties, the ControlToCompare property takes precedence over the ValueToCompare property.
The default comparison operator for the CompareValidator control is equality. However, this is programmable through the Operator property. Valid operators are defined by the ValidationCompareOperator enumeration and include Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck. The DataTypeCheck operator is the only unary operator among them. It is used to determine whether the data in the control identified by the ControlToValidate property is of a certain type. In fact, if you set the ControlToCompare and ValueToCompare properties, they are ignored if the operator type is set to DataTypeCheck. The DataTypeCheck operator uses the value of the Type property as a base for determining the acceptable data type. The Type property is set based on the ValidationDataType enumeration as described in the RangeValidator control previously mentioned.
CustomValidator Control: The controls described up to this point generally focuses on validating one or two fields based on specific, bounded parameters. Typical requirements, however, usually fall outside the capabilities of the intrinsic controls. In anticipation of this, the creators of ASP.NET made the CustomValidator control. The CustomValidator control provides you with an opportunity to create custom validation logic for situations requiring complex business rules validation.
Like other validation controls, the CustomValidator control exposes common properties such as ControlToValidate, Display, ErrorMessage, Text, and ValidationGroup. Also like other validation controls, the CustomValidator control supports both server-side and client-side validation. To associate custom server logic with the control, you must override the ServerValidate event. One of the parameters of the event handler for this event is an object of type ServerValidateEventArgs. Based on the results of the custom validation logic, you can set the IsValid property of the ServerValidateEventArgs object. For client-side validation, you must create a JavaScript function and reference that function using the ClientValidationFunction property of the CustomValidator control.
ValidationSummary Control: In addition to identifying specific fields with data entry problems, it is often useful to provide users with a summary of validation problems on a form. You can use the ValidationSummary control to provide that summary information to users. The ValidationSummary control is used to display the ErrorMessage property values from validation controls on the page when controls being validated are invalid.
Using the ValidationSummary control can improve usability by minimizing distracting and confusing text and by drawing the user's attention to a single location. Displaying specific data validation problems next to each field can consume a lot of screen real estate. In addition, it can cause shifts in screen layout, which leads to confusion. Using a ValidationSummary control concentrates more verbose information in a single location. Good examples of this include placing asterisks or exclamation points next to fields with validation problems.
Validation control grouping has many advantages. First, it improves performance by instructing ASP.NET to perform validation on controls associated with a particular group. To accomplish this, ASP.NET 2.0 adds a ValidationGroup property to other controls that can cause postbacks such as buttons. This means that you can associate a Save button with a particular validation group. The Page class's Validate method is overloaded to accept a validation group name as an input parameter. When all of this is connected, the button instructs the page to perform server-side validation on only those controls in the specified group.
Another advantage of validation control is that it affords you the ability to restrict the information that is presented in a ValidationSummary control. Clearing the ValidationGroup property of the ValidationSummary control effectively associates the summary control with validation controls that also have a non-specified ValidationGroup property. Alternatively, specifying a value for the ValidationGroup property associates the ValidationSummary control with validation controls in the same group.
Summary
CompareValidator: Compares a user value against a constant, another control, or a specific datatype.
CustomValidator: Verifies a user entry against custom code written by a developer. (Values can be derived at run time.)
RangeValidator: Verifies that a user entry is between an upper and a lower bound, using numbers, alphabetic characters, and dates.
RegularExpressionValidator: Verifies that a user entry matches a pattern defined by a regular expression such as e-mail address or telephone number.
RequiredFieldValidator: Verifies that a user enters a value.