Validation Controls

 

Validation Controls

A key rule for writing more secure applications is to get the data right before you use it. Getting the data right requires you to apply a validation step to any external input. In ASP.NET, validation controls provide an easy-to-use mechanism to perform a variety of validation tasks, including testing for valid types, values within a given range, or required fields.

Validation controls inherit from the BaseValidator class which, in turn, descends from Label. All validators defined on a page are automatically grouped in the Validators collection of the Page class. You can validate them all in a single shot using the Validate method in the page class or individually by calling the Validate method on each validator. The Validate method sets the IsValid property both on the page and on the individual validator. The IsValid property indicates whether the user's entries match the requirements of the validators. Other than explicitly using the Validate method, the user's entry is also automatically validated whenever the page posts back.

Note 

In ASP.NET 2.0, typical control members involved with input validation have been grouped in the IValidator interface that the BaseValidator class implements. The interface includes the Validate method and the IsValid and ErrorMessage properties.

The .NET Framework also provides complete client-side implementation for validation controls. This allows Dynamic HTML_enabled browsers (such as Internet Explorer version 4.0 and later) to perform validation on the client as soon as the user tabs out of a monitored input field.

Generalities of Validation Controls

Each validation control references an input control located elsewhere on the page. When the page is going to be submitted, the contents of the monitored server control is passed to the validator for further processing. Each validator would perform a different type of verification. Table 4-12 shows the types of validation supported by the .NET Framework.

Table 4-12: Validator Controls in the .NET Framework

Validator

Description

CompareValidator

Compares the user's entry against a fixed value by using a comparison operator such as LessThan, Equal, or GreaterThan. Can also compare against the value of a property in another control on the same page.

CustomValidator

Employs a programmatically defined validation logic to check the validity of the user's entry. You use this validator when the other validators cannot perform the necessary validation and you want to provide custom code that validates the input.

RangeValidator

Ensures that the user's entry falls within a specified range. Lower and upper boundaries can be expressed as numbers, strings, or dates.

RegularExpressionValidator

Validates the user's entry only if it matches a pattern defined by a regular expression.

RequiredFieldValidator

Ensures that the user specifies a value for the field.

Multiple validation controls can be used with an individual input control to validate according to different criteria. For example, you can apply multiple validation controls on a text box that is expected to contain an e-mail address. In particular, you can impose that the field is not skipped (RequiredFieldValidator) and that its content matches the typical format of e-mail addresses (RegularExpressionValidator).

Table 4-12 lacks a reference to the ValidationSummary control. The control does not perform validation tasks itself. It displays a label to summarize all the validation error messages found on a Web page as the effect of other validators. We'll cover the ValidationSummary control later in the chapter.

The BaseValidator Class

Table 4-13 details the specific properties of validation controls. Some properties such as ForeColor, Enabled, and Text are overridden versions of base properties on base classes.

Table 4-13: Basic Properties of Validators

Property

Description

ControlToValidate

Gets or sets the input control to validate. The control is identified by name that is, by using the value of the ID attribute.

Display

If client-side validation is supported and enabled, gets or sets how the space for the error message should be allocated either statically or dynamically. In case of server-side validation, this property is ignored. A Static display is possible only if the browser supports the display CSS style. The default is Dynamic.

EnableClientScript

True by default; gets or sets whether client-side validation is enabled.

Enabled

Gets or sets whether the validation control is enabled.

ErrorMessage

Gets or sets the text for the error message.

ForeColor

Gets or sets the color of the message displayed when validation fails.

IsValid

Gets or sets whether the associated input control passes validation.

SetFocusOnError

Indicates whether the focus is moved to the control where validation failed. Not available in ASP.NET 1.x.

Text

Gets or sets the description displayed for the validator in lieu of the error message. Note, though, this text does not replace the contents of ErrorMessage in the summary text.

ValidationGroup

Gets or sets the validation group that this control belongs to. Not available in ASP.NET 1.x.

All validation controls inherit from the BaseValidator class except for compare validators, for which a further intermediate class the BaseCompareValidator class exists. The BaseCompareValidator class serves as the foundation for validators that perform typed comparisons. An ad hoc property, named Type, is used to specify the data type the values are converted to before being compared. The CanConvert static method determines whether the user's entry can be converted to the specified data type. Supported types include string, integer, double, date, and currency. The classes acting as compare validators are RangeValidator and CompareValidator.

Associating Validators with Input Controls

The link between each validator and its associated input control is established through the ControlToValidate property. The property must be set to the ID of the input control. If you do not specify a valid input control, an exception will be thrown when the page is rendered. The association validator/control is between two controls within the same container be it a page, user control, or template.

Not all server controls can be validated, only those that specify their validation property through an attribute named [ValidationProperty]. The attribute takes the name of the property that contains the user's entry to check. For example, the validation property for a TextBox is Text and is indicated as follows:

[ValidationProperty("Text")] public class TextBox : WebControl, ITextControl {     ... } 

The list of controls that support validation includes TextBox, DropDownList, ListBox, RadioButtonList, FileUpload, plus a bunch of HTML controls such as HtmlInputFile, HtmlInputText, HtmlInputPassword, HtmlTextArea, and HtmlSelect. Custom controls can be validated too, as long as they are marked with the aforementioned [ValidationProperty] attribute.

Note 

If the validation property of the associated input control is left empty, all validators accept the value and pass the test. The RequiredFieldValidator control represents a rather natural exception to this rule as it has been specifically designed to detect fields the user skipped and left blank.

Gallery of Controls

Let's take a closer look at the various types of validation controls that you'll use in ASP.NET Web forms.

The CompareValidator Control

The CompareValidator control lets you compare the value entered by the user with a constant value or the value specified in another control in the same naming container. The behavior of the control is characterized by the following additional properties:

The following code demonstrates the typical markup of the CompareValidator control when the control is called to validate an integer input from a text box representing someone's age:

<asp:CompareValidator runat="server"      ControlToValidate="ageTextBox"     ValueToCompare="18"     Operator="GreaterThanEqual"     Type="Integer"     ErrorMessage="Must specify an age greater than 17." /> 

The CustomValidator Control

The CustomValidator control is a generic and totally user-defined validator that uses custom validation logic to accomplish its task. You typically resort to this control when none of the other validators seems appropriate or, more simply, when you need to execute your own code in addition to that of the standard validators.

To set up a custom validator, you can indicate a client-side function through the ClientValidationFunction property. If client-side validation is disabled or not supported, simply omit this setting. Alternatively, or in addition to client validation, you can define some managed code to execute on the server. You do this by defining a handler for the ServerValidate event. The code will be executed when the page is posted back in response to a click on a button control. The following code snippet shows how to configure a custom validator to check the value of a text box against an array of feasible values:

<asp:CustomValidator runat="server"      ControlToValidate="membership"     ClientValidationFunction="CheckMembership"     OnServerValidate="ServerValidation"     ErrorMessage="Membership can be Normal, Silver, Gold, or Platinum." /> 

If specified, the client validation function takes a mandatory signature and looks like this:

function CheckMembership(source, arguments) { ... } 

The source argument references the HTML tag that represents the validator control usually, a <span> tag. The arguments parameter references an object with two properties, IsValid and Value. The Value property is the value stored in the input control to be validated. The IsValid property must be set to false or true according to the result of the validation.

The CustomValidator control is not associated in all cases with a single input control in the current naming container. For this type of validator, setting the ControlToValidate property is not mandatory. For example, if the control has to validate the contents of multiple input fields, you do not simply set the ControlToValidate property and the arguments.Value variable evaluates to the empty string. In this case, you write the validation logic so that any needed values are dynamically retrieved. With client-side script code, this can be done by accessing the members of the document's form, as shown in the following code:

function CheckMembership(source, arguments) {     // Retrieve the current value of the element     // with the specified ID     var membership = document.forms[0]["membership"].value;     ... } 
Warning 

Setting only a client-side validation code opens a security hole because an attacker could work around the validation logic and manage to have invalid or malicious data sent to the server. By defining a server event handler, you have one more chance to validate data before applying changes to the back-end system.

To define a server-side handler for a custom validator, use the ServerValidate event:

void ServerValidation(object source, ServerValidateEventArgs e) {     ... } 

The ServerValidateEventArgs structure contains two properties IsValid and Value with the same meaning and goal as in the client validation function. If the control is not bound to a particular input field, the Value property is empty and you retrieve any needed value using the ASP.NET object model. For example, the following code shows how to check the status of a check box on the server:

void ServerValidation (object source, ServerValidateEventArgs e) {     e.IsValid = (CheckBox1.Checked == true); } 

The CustomValidator control is the only option you have to validate controls that are not marked with the [ValidationProperty] attribute for example, calendars and check-box controls.

The RegularExpressionValidator Control

Regular expressions are an effective way to ensure that a predictable and well-known sequence of characters form the user's entry. For example, using regular expressions, you can validate the format of Zip Codes, Social Security numbers, e-mail addresses, phone numbers, and so on. When using the RegularExpressionValidator control, you set the ValidationExpression property with the regular expression, which will be used to validate the input.

The following code snippet shows a regular expression validator that ensures the user's entry is an e-mail address:

<asp:RegularExpressionValidator runat="server"      ControlToValidate="email"     ValidationExpression="[a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+"     ErrorMessage="Must be a valid email address." /> 

The regular expression just shown specifies that valid e-mail addresses are formed by two nonzero sequences of letters, digits, dashes, and dots separated by an @ symbol and followed by a dot (.) and an alphabetic string. (This might not be the perfect regular expression for e-mail addresses, but it certainly incorporates the majority of e-mail address formats.)

Note 

The regular expression validation syntax is slightly different on the client than on the server. The RegularExpressionValidator control uses Microsoft JScript regular expressions on the client and the .NET Framework Regex object on the server. Be aware that the JScript regular expression syntax is a subset of the Regex model. Whenever possible, try to use the regular expression syntax supported by JScript so that the same result is obtained for both the client and server.

The RangeValidator Control

The RangeValidator control lets you verify that a given value falls within a specified range. The type of the values involved in the check is specified dynamically and picked from a short list that includes strings, numbers, and dates. The following code shows how to use a range validator control:

<asp:RangeValidator runat="server"      ControlToValidate="hired"     MinimumValue="2000-1-4"     MaximumValue="9999-12-31"     Type="Date"     ErrorMessage="Must be a date after <b>Jan 1, 1999</b>." /> 

The key properties are MinimumValue and MaximumValue, which together clearly denote the lower and upper boundaries of the interval. Note that an exception is thrown if the strings assigned MinimumValue or MaximumValue cannot be converted to the numbers or dates according to the value of the Type property.

If the type is set to Date, but no specific culture is set for the application, you should specify dates using a culture-neutral format, such as yyyy-MM-dd. If you don't do so, the chances are good that the values will not be interpreted correctly.

Note 

The RangeValidator control extends the capabilities of the more basic CompareValidator control by checking for a value in a fixed interval. In light of this, the RangeValidator control might raise an exception if either MinimumValue or MaximumValue is omitted. Whether the exception is thrown depends on the type chosen and its inherent ability to interpret the empty string. For example, an empty string on a Date type causes an exception. If you want to operate on an unbound interval whether lower or upper unbound either you resort to the GreaterThan (or LessThan) operator on the CompareValidator control or simply use a virtually infinite value, such as the 9999-12-31 value.

The RequiredFieldValidator Control

To catch when a user skips a mandatory field in an input form, you use the RequiredFieldValidator control to show an appropriate error message:

<asp:RequiredFieldValidator runat="server"      ControlToValidate="lname"     ErrorMessage="Last name is mandatory" /> 

As long as you're using an up-level browser and client-side scripting is enabled for each validator, which is the default, invalid input will display error messages without performing a postback.

Important 

Note that just tabbing through the controls is not a condition that raises an error; the validator gets involved only if you type blanks or if the field is blank when the page is posted back.

How can you determine whether a certain field is really empty? In many cases, the empty string is sufficient, but this is not a firm rule. The InitialValue property specifies the initial value of the input control. The validation fails only if the value of the control equals InitialValue upon losing focus. By default, InitialValue is initialized with the empty string.

Special Capabilities

The primary reason why you place validation controls on a Web form is to catch errors and inconsistencies in the user's input. But how do you display error messages? Are you interested in client-side validation and, if so, how would you set it up? Finally, what if you want to validate only a subset of controls when a given button is clicked? Special capabilities of validation controls provide a valid answer to all these issues.

Displaying Error Information

The ErrorMessage property determines the static message that each validation control will display in case of error. It is important to know that if the Text property is also set, it would take precedence over ErrorMessage. Text is designed to display inline where the validation control is located; ErrorMessage is designed to display in the validation summary. (Strategies for using Text and ErrorMessage will be discussed more in the next section, "The ValidationSummary Control.") Because all validation controls are labels, no other support or helper controls are needed to display any message. The message will be displayed in the body of the validation controls and, subsequently, wherever the validation control is actually placed. The error message is displayed as HTML, so it can contain any HTML formatting attribute.

Validators that work in client mode can create the <span> tag for the message either statically or dynamically. You can control this setting by using the Display property of the validator. When the display mode is set to Static (the default), the <span> element is given the following style:

style="color:Red;visibility:hidden;" 

The CSS visibility style attribute, when set to Hidden, causes the browser not to display the element but reserves space for it. If the Display property contains Dynamic, the style string changes as follows:

style="color:Red;display:none;" 

The CSS display attribute, when set to none, simply hides the element, which will take up space on the page only if displayed. The value of the Display property becomes critical when you have multiple validators associated with the same input control. (See Figure 4-7.)

image from book
Figure 4-7: Input controls in the form are validated on the client.

As you can see, the hire text box is first validated to ensure it contains a valid date and then to verify the specified date is later than 1-1-1999. If the Display property is set to Static for the first validator, and the date is outside the specified range, you get a page like the one shown in Figure 4-8.

image from book
Figure 4-8: Static error messages take up space even if they're not displayed.

The full source code of the page in the figure is available on the Web at the following address: http://www.microsoft.com/mspress/companion/0-7356-2176-4.

Note 

You can associate multiple validators with a single input control. The validation takes place in order, and each validation control generates and displays its own error message. The content of the input control is considered valid if all the validators return true. If an input control has multiple valid patterns for example, an ID field can take the form of a Social Security number or a VAT number you can either validate by using custom code or regular expressions.

The ValidationSummary Control

The ValidationSummary control is a label that summarizes and displays all the validation error messages found on a Web page after a postback. The summary is displayed in a single location formatted in a variety of ways. The DisplayMode property sets the output format, which can be a list, a bulleted list, or a plain text paragraph. By default, it is a bulleted list. The feasible values are grouped in the ValidationSummaryDisplayMode enumeration.

Whatever the format is, the summary can be displayed as text in the page, in a message box, or in both. The Boolean properties ShowSummary and ShowMessageBox let you decide. The output of the ValidationSummary control is not displayed until the page posts back no matter what the value of the EnableClientScript property is. The HeaderText property defines the text that is displayed atop the summary:

<asp:ValidationSummary runat="server"     ShowMessageBox="true"     ShowSummary="true"     HeaderText="The following errors occurred:"     DisplayMode="BulletList" /> 

This code snippet originates the screen shown in Figure 4-9.

image from book
Figure 4-9: After the page posts back, the validation summary is updated and a message box pops up to inform the user.

The validation summary is displayed only if there's at least one pending error. Notice that in the default case, the labels near the input controls are updated anyway, along with the summary text. In summary, you can control the error information in the following ways:

Enabling Client Validation

As mentioned earlier, the verification normally takes place on the server as the result of the postback event or after the Validate method is called. If the browser supports Dynamic HTML, though, you can also activate the validation process on the client, with a significant gain in responsiveness. To be precise, ASP.NET automatically enables client-side validation if it detects a browser with enough capabilities. While ASP.NET 1.x limits its client-side support only to Internet Explorer 4.0 or higher, in ASP.NET 2.0 validation controls also work fine on the client with Mozilla Firefox, Netscape 6.x, and Safari 1.2. Figure 4-10 shows the previous sample page in action in Mozilla Firefox.

image from book
Figure 4-10: Client-side validation active also in Mozilla Firefox.

If client-side validation is turned on, the page won't post back until all the input fields contain valid data. To run secure code and prevent malicious and underhanded attacks, you might want to validate data on the server, too. Consider also that not all types of validation can be accomplished on the client. In fact, if you need to validate against a database, there's no other option than posting back to the server.

Client validation can be controlled on a per-validation control basis by using the EnableClientScript Boolean property. By default, the property is set to true, meaning client validation is enabled as long as the browser supports it. By default, the code in the BaseValidator class detects the browser's capabilities through the Request.Browser property. If the browser is considered up-level, the client validation will be implemented. Browsers and client devices that are considered up-level support at least the following:

For down-level browsers, the only requirement is HTML version 3.2. You can also control the client validation at the page level by using the ClientTarget attribute on the @Page directive. The following code disables client validation by specifying that any code in the page should target a down-level browser:

<% @Page ClientTarget="DownLevel" %> 

The ClientTarget attribute overrides the type of browser that ASP.NET should target when generating the page. When the ClientTarget attribute is set, ASP.NET doesn't detect the actual browser's capabilities but instead loads the capabilities for the specified browser from the browser database.

Validation Groups

In ASP.NET 1.x, control validation occurs in an all-or-nothing kind of way. For example, if you have a set of input and validation controls and two buttons on the form, clicking either button will always validate all controls. In other words, there's no way to validate some controls when one button is clicked, and some others when the other button is clicked. The CausesValidation property on button controls allows you to disable validation on a button, but that is not the point here. What is missing is the ability to do validation on a group of controls. This is exactly what the ValidationGroup property provides in ASP.NET 2.0. The property is available on validators, input controls, and button controls.

Using the ValidationGroup property is simple; just define it for all the validation controls that you want to group together, and then assign the same name to the ValidationGroup property of the button that you want to fire the validation. Here's an example:

<asp:textbox runat="server"  /> <asp:RequiredFieldValidator runat="server"     ValidationGroup="Group1"     ControlToValidate="TextBox1"     ErrorMessage="TextBox1 is mandatory" /> <asp:textbox runat="server"  /> <asp:RequiredFieldValidator runat="server"     ValidationGroup="Group2"     ControlToValidate="TextBox2"     ErrorMessage="TextBox2 is mandatory" /> <asp:Button runat="server" Text="Check Group1" ValidationGroup="Group1" /> <asp:Button runat="server" Text="Check Group2" ValidationGroup="Group2" /> 

The two RequiredFieldValidator controls belong to distinct validation groups Group1 and Group2. The first button validates only the controls defined within Group1; the second button takes care of the input associated with Group2. In this way, the validation process can be made as granular as needed.

Important 

The ValidationGroup property can optionally be defined also on input controls. This is required only if you use the CustomValidator control as a way to check whether a given input control belongs to the right validation group.

The validation group feature becomes especially helpful when combined with cross-page postbacks an ASP.NET 2.0 feature that we'll cover in the next chapter. Cross-page postback allows a button to post the contents of the current form to another page, in a certain way overriding the single-form model of ASP.NET. Imagine you have a search box in your page, and you want to post its contents directly to a search page without passing through the classic postback mechanism and an additional redirect. Validation groups allow you to check only the contents of the search text box prior to posting to the search page.

Validation groups are also reflected on the server-side where the Validate method of the Page class now features an overload that lets you select the group according to which the page must be validated.

 


Programming Microsoft ASP. Net 2.0 Core Reference
Programming Microsoft ASP.NET 2.0 Core Reference
ISBN: 0735621764
EAN: 2147483647
Year: 2004
Pages: 112
Authors: Dino Esposito
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net