• No results found

Using Validation Controls

Book VIII: Advanced ASP.NET Programming

Chapter 2: Using Validation Controls

In This Chapter

Using validation controls to validate user input

Working with advanced validation controls

Adding a validation summary to a page

Validating more than one group of input fields

V

alidation is one of the most important parts of any type of computer programming. The moment you expose your program to the outside world by asking a user to input some data, the possibility arises that the user will enter the wrong data, or that the user will forget to enter any data at all. To get any real work done, ASP.NET programs need to protect them- selves from such errors and omissions.

You won’t be able to catch all the errors a user might make. For example, a user might spell his or her name wrong (due to a bad day, lack of coffee, or whatever). But you can detect and prevent common types of errors. For example, you can require that the user enter some data into a text box — and, if the text box is supposed to contain a number, you can require that the user enter a valid number. This chapter shows how to do that and more. All code listings used in this book are available for download at www.dummies. com/go/aspnetaiofd.

Validating the Hard Way

In Book 1, I present a simple calculator program that added two numbers entered by the user. In real-world terms, that program is a little too simple; it didn’t include any validation code. It would crash if the user failed to enter correct numeric data.

One way — okay, the hard way — to add validation code to that program (or to any other program) is to type in some code that checks the validity of each input field before the program acts on the data. The program will dis- play an error message if any incorrect data is detected.

Validating the Hard Way

116

For a glimpse of what this approach would look like, consider the following

.aspxfile: <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Simple Calculator</title> </head> <body>

<form id=”form1” runat=”server”>

<asp:Label ID=”Label1” runat=”server” Text=”First name:” />

<asp:TextBox ID=”txtFirstName” runat=”server” /> <asp:Label ID=”lblErrorFirstName” runat=”server”

ForeColor=”Red” EnableViewState=”False” /> <br />

<asp:Label ID=”Label2” runat=”server” Text=”Last name:” />

<asp:TextBox ID=”txtLastName” runat=”server” /> <asp:Label ID=”lblErrorLastName” runat=”server”

ForeColor=”Red” EnableViewState=”False” /> <br /><br />

<asp:Button ID=”btnSubmit” runat=”server” Text=”Submit” OnClick=”btnAdd_Click” /> <br /><br />

<asp:Label ID=”lblValid” runat=”server” /> </form>

</body> </html>

This page displays two text boxes, named txtFirstNameand txtLastName. Next to the text boxes are labels named lblErrorFirstNameand lblError LastName. A button named btnSubmitlets the user submit the first and last name he or she entered, and a final label named lblValidis used to display a message that indicates whether the user entered valid data.

The validation requirements for this page are simple: The user must enter something in both of the text boxes. Here’s the Clickevent handler for the

Submitbutton:

protected void btnAdd_Click(object sender, EventArgs e) {

if (validData())

lblValid.Text = “You entered valid data.”; else

lblValid.Text = “You did not enter valid data.”; }

Book II Chapter 2

Using V

alidation

Controls

Validation Controls to the Rescue!

117

As you can see, the Clickevent handler calls a method named validDatato determine if the user entered correct data. This method is defined as follows:

private boolean validData() {

boolean valid = true;

if (txtFirstName.Text == “”) { lblErrorFirstName.Text = “Required field.”; valid = false; } if (txtLastName.Text == “”) { lblErrorLastName.Text = “Required field.”; valid = false; } return valid; }

Figure 2-1 shows this page in action. Here you can see an error message dis- played for the LastNametext box because the user didn’t enter a last name.

That’s a lot of work just to make sure the user has entered some data. As the next section reveals, however, this type of code is rarely necessary in ASP.NET applications.

Validation Controls to the Rescue!

The good folks at Microsoft realized that most ASP.NET applications would need to validate input data, and that programmers like to write as little code

Figure 2-1: A page that does validate input data manually.

Using the RequiredFieldValidator Control

118

as possible. To meet both criteria, they created a collection of handy valida- tion controlsthat can automatically validate input data, with little or no code required.

These validation controls live in the Validation section of the toolbox. (The Validation section is the third section of the toolbox, beneath the Standard controls and the Data controls.) There are six different validation controls you can use:

✦ RequiredFieldValidator:This is most popular of the validation con- trols. It requires the user to enter some value in a field. Any value will do, but the user must enter something.

✦ CompareValidator:This validator compares the value entered by the user with some predetermined value. One of the most common uses of this validator is to ensure that the user enters data of the correct type. For example, if a text box requires numeric input, you can use a

CompareValidatorto make sure the user enters a valid number.

✦ RangeValidator:This validator makes sure that the value entered by the user falls within a given range.

✦ RegularExpressionValidator:This validator makes sure that the user enters a value that matches a pattern. For example, you can use this validator for Zip codes, telephone numbers, and so on.

✦ CustomValidator:This validator lets you write your own code to deter- mine whether the user entered correct input data.

✦ ValidationSummary:This control is used along with other validation controls to display a summary message that lists all errors discovered on the page.

As with any other ASP.NET control, you can add a validator to a page by dragging it from the toolbox onto the page. If you’re working in Design view, you can use the Properties window to set the properties of the validator con- trol. If you prefer to work in Source view, you can edit the markup directly to set the validator’s properties.

Using the RequiredFieldValidator Control

The most basic type of ASP.NET validation control is the required field valida- tor. As its name implies, it requires the user to enter some value — any value will do — into an input field. RequiredFieldValidatorcontrols are used most often with TextBoxcontrols, but you can use them with other types of input controls as well.

Book II Chapter 2

Using V

alidation

Controls

Using the RequiredFieldValidator Control

119

Besides the ubiquitous IDand Runatattributes, a RequiredFieldValidator

control has two important attributes you should always set:

✦ ControlToValidate:Provides the IDof the input control that the required field validator should be associated with.

✦ ErrorMessage: Provides the text that the validator control will display if the user doesn’t enter any data into the associated input control. For example, here’s a typical RequiredFieldValidatorcontrol:

<asp:RequiredFieldValidator ID=”RequiredFieldValidator2” runat=”server”

ControlToValidate=”txtLastName” ErrorMessage=”Required field.” />

Here the required field validator is associated with the control named

txtLastNameand the error message is “Required field.”

You should place the RequiredFieldValidatorcontrol where you want the error message to be displayed if the user fails to enter a value. Listing 2-1 provides the complete .aspxfile that creates a page similar to the one shown in Figure 2-1:

Listing 2-1: A complete .aspx file for validating input data (C#)

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Simple Calculator</title> </head> <body>

<form id=”form1” runat=”server”>

<asp:Label ID=”Label1” runat=”server” Text=”First name:” />

<asp:TextBox ID=”txtFirstName” runat=”server” />&nbsp; <asp:RequiredFieldValidator ID=”RequiredFieldValidator1”

runat=”server”

ControlToValidate=”txtFirstName” ErrorMessage=”Required field.” /> <br />

<asp:Label ID=”Label2” runat=”server” Text=”Last name:” />

<asp:TextBox ID=”txtLastName” runat=”server” />&nbsp;

Using the CompareValidator Control

120

Listing 2-1 (continued) <asp:RequiredFieldValidator ID=”RequiredFieldValidator2” runat=”server” ControlToValidate=”txtLastName” ErrorMessage=”Required field.” /> <br /><br />

<asp:Button ID=”btnSubmit” runat=”server”

Text=”Submit” OnClick=”btnAdd_Click” /><br /><br /> </form>

</body> </html>

Here the two labels named lblErrorFirstNameand lblErrorLastName

have been replaced by required field validators that automatically validate the text boxes. No server-side code is required to validate the input data. It’s important to understand that ASP.NET validators use client-side code to perform their validation. Thus, if the user clicks a Submit button and the val- idators determine that at least one of the input fields on the page contains invalid data, the page won’t be posted to the server. (The validation controls also use server-side code to check the data’s validity. That’s necessary because it’s possible for the user to disable or bypass the client-side code.)

Using the CompareValidator Control

Next to the RequiredFieldValidatorcontrol, the CompareValidatorcon- trol is probably the validator you’ll use most. It performs several basic types of comparison checks on an input field. It can perform the following basic types of comparisons:

Constant comparisons, in which the value entered by the user is compared with a constant value.For example, you can ensure that a numeric value is greater than zero.

Comparisons with other controls, in which the value entered by the user is compared with the value entered for another control.For example, if a page has fields that let the user enter a start date and an end date, you can use a CompareValidatorcontrol to make sure that the end date does not occur before the start date.

Type comparisons, which let you verify that the user has entered the correct type of data.This is one of the most useful types of compar- isons performed by the CompareValidatorcontrol.

The following table lists the properties you’re most likely to set for the

Book II Chapter 2

Using V

alidation

Controls

Using the CompareValidator Control

121

Property Description

ControlToValidate The IDof the input control you want to validate. ErrorMessage The error message displayed if the control fails

the validation.

ValueToCompare The value that the control should be compared to. ControlToCompare The IDof another control that will supply the

value to compare.

Operator The comparison operation to perform. You can specify Equal, NotEqual, LessThan, Less ThanEqual, GreaterThan, GreaterThan Equal, or DataTypeCheck.

Type The data type. You can specify String,

Integer, Double, Date, or Currency.

If the user doesn’t enter any data into a control, the validator doesn’t do the comparison. Accordingly, you should always include a RequiredField Validatorcontrol if you want to require the user to enter a value.

When you use more than one validator for a single control, you’ll usually want to set the validator’s Displayproperty to Dynamic. This property sets the width of the control to zero if the validation succeeds. If you leave the

Displayproperty set to its default (Static), the validator takes up space on the page even if no error message is displayed.

Here’s an example of a text box that has a RequiredFieldValidatorcontrol and a CompareValidatorcontrol that makes sure the value is an integer:

<asp:TextBox ID=”txtQuantity” runat=”server” />

<asp:RequiredFieldValidator ID=”RequiredFieldValidator1” runat=”server” ControlToValidate=”txtQuantity” Display=”Dynamic” ErrorMessage=”Required field.” /> <asp:CompareValidator ID=”CompareValidator1” runat=”server” ControlToValidate=”txtQuantity” Display=”Dynamic” ErrorMessage=”Must be a number.“ Operator=”DataTypeCheck” Type=”Integer” />

Note that if you use an operator other than DataTypeCheck, a data-type check happens automatically. That means you don’t need to use a separate

Using the RangeValidator Control

122

For example, suppose you want to make sure a field is entered, is a valid number, and is greater than zero. In that case, the following validators will do the job:

<asp:TextBox ID=”txtQuantity” runat=”server” />

<asp:RequiredFieldValidator ID=”RequiredFieldValidator1” runat=”server” ControlToValidate=”txtQuantity” Display=”Dynamic” ErrorMessage=”Required field.” /> <asp:CompareValidator ID=”CompareValidator2” runat=”server” ControlToValidate=”txtQuantity”

ErrorMessage=”Must be greater than zero.“ Type=”Integer”

Operator=”GreaterThan” ValueToCompare=”0” />

Using the RangeValidator Control

The RangeValidatorcontrol is similar to the CompareValidatorcontrol, but instead of doing a single comparison check, it does two checks to make sure the value entered by the user falls within a particular range of values. Here’s a table that sums up the properties you can use with the RangeValidator

control:

Property Description

ControlToValidate The ID of the input control to validate.

ErrorMessage The error message displayed if the control fails the validation.

MinimumValue The smallest acceptable value. MaximumValue The largest acceptable value.

Type The data type. You can specify String,

Integer, Double, Date, or Currency.

Here’s an example of a RangeValidatorcontrol that makes sure a value falls between 0and 100:

<asp:RangeValidator ID=”RangeValidator1” runat=”server” ControlToValidate=”TextBox1”

Display=”Dynamic”

ErrorMessage=”Must be between 0 and 100. “ MinimumValue=”0”

MaximumValue=”100” Type=”Integer” />

Book II Chapter 2

Using V

alidation

Controls

Using the RegularExpressionValidator

123

Using the RegularExpressionValidator

Many types of data-entry fields follow standard patterns. For example, U.S. phone numbers follow the pattern (nnn) nnn-nnnn, and U.S. Zip codes are either nnnnnor nnnnn-nnnn.

The RegularExpressionValidatorcontrol is designed to let you validate data against patterns like this. The term regular expression refers to a some- what standardized language used to define these patterns. Regular expres- sions can be extremely powerful, and also extremely confusing. A complete discussion of regular expressions would fill an entire chapter, but you’ll find a description of the basics in this chapter’s sidebar, “Using Regular Expressions.”

You use the ValidationExpressionproperty to specify the regular expres- sion you want to use for the validation. For example, here’s an example of a

RegularExpressionValidatorcontrol that validates a U.S. Social Security number: <asp:RegularExpressionValidator ID=”RegularExpressionValidator1” runat=”server” ControlToValidate=”txtSSN” ErrorMessage=”Invalid entry.” ValidationExpression=”\d{3}-\d{2}-\d{4}” />

Fortunately, Visual Studio provides several predefined regular expressions you can use with the RegularExpressionValidatorcontrol. The pre-defined expressions are listed in Table 2-1. To use one of these expressions, select a RegularExpressionValidatorcontrol in the Web designer, and then double-click the ellipses that appear next to the ValidationExpression

property in the Properties window. Doing so brings up the dialog box shown in Figure 2-2, from which you can choose the expression you want to use.

Figure 2-2:

Choosing a predefined regular expression.

Using the RegularExpressionValidator

124

Table 2-1 Predefined Regular Expressions

Name Expression

French phone number (0( \d|\d ))?\d\d \d\d(\d \d| \d\d )

\d\d

French postal code \d{5}

German phone number ((\(0\d\d\) |(\(0\d{3}\) )?\d )?\d\d

\d\d \d\d|\(0\d{4}\) \d \d\d-\d\d?)

German postal code (D-)?\d{5}

Internet e-mail address \w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+ ([-.]\w+)*

Internet URL http(s)?://([\w-]+\.)+[\w-]+

(/[\w- ./?%&=]*)?

Japanese phone number (0\d{1,4}-|\(0\d{1,4}\) ?)?\d{1,4}-\

d{4}

Japanese postal code \d{3}(-(\d{4}|\d{2}))?

P.R.C. phone number (\(\d{3}\)|\d{3}-)?\d{8}

P.R.C. postal code \d{6}

P.R.C. Social Security number \d{17}[\d|X]|\d{15}

U.S. phone number ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}

U.S. Social Security number \d{3}-\d{2}-\d{4}

U.S. Zip code \d{5}(-\d{4})?

Using regular expressions

Most regular expressions simply match char- acters to see if a string complies with a simple pattern. For example, you can check a string to see whether it matches the format for Social Security numbers, phone numbers, or more complicated patterns such as e-mail addresses. You can match a specific character in a regular expression by including the character directly in the expression. For example, the expression abcwill match only the string abc.

More useful expressions use character classes that represent a particular type of character rather than a specific character. There are two types of character classes: predefined classes

and custom classes. The predefined character classes are as follows:

.:Any character \d:Any digit (0–9)

\D:Any non-digit (anything other than 0–9) \s: Any white-space character (such as spaces, tabs, newlines, returns, and backspaces)

\S: Any character other than a white space character

\w:Any word character (a–z, A–Z, 0–9, or an underscore)

Book II Chapter 2

Using V

alidation

Controls

Using a CustomValidator Control

125

\W: Any character other than a word character

The period is like a wildcard that matches any single character. For example, the expression c.tmatches strings such as catand cotbut not cart.

The \d class represents a digit. Here’s the expression \d\d\d-\d\d-\d\d\d\dthat validates U.S. Social Security numbers. The \d class has a counterpart — \D — which matches any character that is not a digit. The \sclass matches white-space characters including spaces, tabs, newlines, returns, and backspaces. This class is useful when you want to allow the user to separate parts of a string in various ways.

The last set of predefined classes are \wand \W. The \wclass identifies any character that’s normally used in words. Such characters include upper- and lowercase letters, digits, and the underscore.

You can add the following quantifiers to an expression to create patterns that match a vari- able number of characters at a certain position in the string:

?:Zero or one times *:Zero or more times +:One or more times