|
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Chapter 3: Performing Form Validation with Validation ControlsIn This Chapter
In this chapter, you learn how to use the Validation Web controls to validate the information that a user enters into an HTML form. You can use the Validation controls to perform very different types of form validation tasks. For example, you can use the Validation controls to check whether a form field has a value, check whether the data in a form field falls in a certain range, or check whether a form field contains a valid e-mail address or phone number.
At the end of this chapter, you also learn how to create custom validation functions by using the CustomValidator control. Even if you need to perform a very specialized form validation task, you can do so by using this control. Using Client-side ValidationTraditionally, Web developers have faced a tough choice when adding form validation logic to their pages. You can add form validation routines to your server-side code, or you can add the validation routines to your client-side code. The advantage of writing validation logic in client-side code is that you can provide instant feedback to your users. For example, if a user neglects to enter a value in a required form field, you can instantly display an error message without requiring a roundtrip back to the server. People really like client-side validation. It looks great and creates a better overall user experience. The problem, however, is that it does not work with all browsers. Not all browsers support JavaScript, and different versions of browsers support different versions of JavaScript, so client-side validation is never guaranteed to work. For this reason, in the past, many developers decided to add all their form validation logic exclusively to server-side code. Because server-side code functions correctly with any browser, this course of action was safer. Fortunately, the Validation controls discussed in this chapter do not force you to make this difficult choice. The Validation controls automatically generate both client-side and server-side code. If a browser is capable of supporting JavaScript, client-side validation scripts are automatically sent to the browser. If a browser is incapable of supporting JavaScript, the validation routines are automatically implemented in server-side code. You should be warned, however, that client-side validation works only with Microsoft Internet Explorer version 4.0 and higher. In particular, the client-side scripts discussed in this chapter do not work with any version of Netscape Navigator. Configuring Client-side ValidationThe Validation controls make use of a JavaScript script library that is automatically installed on your server when you install the .NET framework. This library is located in a file named WebUIValidation.js. By default, WebUIValidation.js is installed in a directory named aspnet_client located beneath your Web server's wwwroot directory. If you change the location of your root directory, you need to copy the aspnet_client directory to the new directory; otherwise, the validation script will not work. If WebUIValidation.js can't be found, you receive the error Warning! Unable to find script library 'WebUIValidation.js' (see Figure 3.1). Figure 3.1
Microsoft includes a command line tool with the ASP.NET Framework named aspnet_regiis that you can use to automatically install and uninstall the script library. To install the script library execute aspnet_regiis -c, to uninstall the library execute aspnet_regiis -e. The aspnet_regiis tool is located in your \WINNT\Microsoft.NET\Framework\[version]\ directory. Enabling and Disabling Client-side ValidationIf you request a page that contains a validation control, and you are using Microsoft Internet Explorer version 4.0 or higher, JavaScript code is automatically sent to your browser. If, for whatever reason, you want to disable client-side form validation, you can do so by adding the following directive at the top of your page: <%@ Page ClientTarget="downlevel" %> This directive disables client-side form validation. Unfortunately, however, it also prevents all the ASP.NET controls on the page from rendering any non-HTML 3.2 compatible content. For example, the directive also prevents the rendering of Cascading Style Sheet attributes to the page.
Alternatively, you can disable client-side validation for individual validation controls by setting the EnableClientScript property to the value False. Since all validation controls share the EnableClientScript property, you can use this property to disable client-side scripts for particular validation controls or for all validation controls. Finally, you can disable validation, both client and server validation, when certain buttons are pushed. You'll need to do this when creating a Cancel button. See the last section of this chapter, Disabling Validation, for sample code that demonstrates how to do this. Requiring Fields: The RequiredFieldValidator ControlYou use RequiredFieldValidator in a Web form to check whether a control has a value. Typically, you use this control with a TextBox control. However, nothing is wrong with using RequiredFieldValidator with other input controls such as RadioButtonList. All the properties and methods of this control are listed in Table 3.1. Table 3.1 RequiredFieldValidator Properties, Methods, and Events
The page in Listing 3.1, for example, contains two TextBox controls named txtUsername and txtComments. Each TextBox control has a RequiredFieldValidator control associated with it. If you attempt to submit the form without entering data into both TextBox controls, you get an error. Listing 3.1 RequiredFieldValidator.aspx<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) If IsValid Then Response.Redirect( "ThankYou.aspx" ) End If End Sub </Script> <html> <head><title>RequiredFieldValidator.aspx</title></head> <body> <form Runat="Server"> Username: <br><asp:TextBox ID="txtUsername" Runat="Server" /> <asp:RequiredFieldValidator ControlToValidate="txtUsername" Text="You must enter a username!" Runat="Server" /> <p> Comments: <br> <asp:TextBox id="txtComments" TextMode="MultiLine" Runat="Server"/> <asp:RequiredFieldValidator ControlToValidate="txtComments" Text="You must enter some comments!" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> If you do not enter any text into the TextBox controls and you submit the form, the RequiredFieldValidator controls display error messages, and the IsValid property has the value False. Otherwise, the Button_Click subroutine automatically redirects you to a page named ThankYou.aspx. When performing form validation, you can check the IsValid property for each Validation control to check whether each form field was completed successfully. Alternatively, you can simply check the IsValid property of the page. The Page.IsValid property is True only if the IsValid property is True for every Validation control on the page. The RequiredFieldValidator controls are associated with the TextBox controls through the ControlToValidate property. For example, the first RequiredFieldValidator control is associated with the txtUsername control because its ControlToValidate property has the value txtUsername. The error message that each RequiredFieldValidator displays is determined by the Text property. By default, the text is displayed in a red font. You can determine precisely how the error message is formatted by using the formatting properties discussed in the final section of the preceding chapter, "Building Forms with Web Server Controls." If you want to display a blue error message using a Script font, for example, you would declare RequiredFieldValidator with the following properties: <asp:RequiredFieldValidator ForeColor="Blue" Font-Name="Script" ControlToValidate="txtUsername" Text="You must enter a username!" Runat="Server" /> You also can control how the error messages appear by modifying the Display property. By default, screen real estate is reserved for an error message, even if the error message is not displayed. However, if you assign the value Dynamic to the Display property, the error message pushes away any content surrounding it. The page in Listing 3.2, for example, contains two RequiredFieldValidator controls. The first RequiredFieldValidator control has its Display property set to Static; the second has its Display property set to Dynamic. Listing 3.2 RequiredFieldValidatorDisplay.aspx<html> <head><title>RequiredFieldValidatorDisplay.aspx</title></head> <body> <form Runat="Server"> Field 1: <br><asp:TextBox id="txtField1" Runat="Server" /> <asp:RequiredFieldValidator ControlToValidate="txtField1" Text="You must enter a value for field1!" Runat="Server" /> Here is Some Text <p> Field 2: <br> <asp:TextBox id="txtField2" Runat="Server"/> <asp:RequiredFieldValidator ControlToValidate="txtField2" Text="You must enter a value for field2!" Display="Dynamic" Runat="Server" /> Here is Some Text <p> <asp:Button Text="Submit" Runat="Server"/> </form> </body> </html> The text, Here is Some Text, is written next to each RequiredFieldValidator. Notice how the text after the first RequiredFieldValidator control is pushed to the right (see Figure 3.2). Figure 3.2 Comparing to an Initial ValueYou also can use RequiredFieldValidator to check whether a user has entered a value other than an initial value. You might want to display a sample of the type of input that a user should enter into a form field, but require a different value to be entered into the form field before the form is submitted. For example, you might want to display the text Enter Some Text within a text box. However, you would not want the user to actually submit the value Enter Some Text when the form is submitted. The page in Listing 3.3 demonstrates how to use the InitialValue property of the RequiredFieldValidator control. Listing 3.3 RequiredFieldValidatorInitialValue.aspx<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) If IsValid Then Response.Redirect( "ThankYou.aspx" ) End If End Sub </Script> <html> <head><title>RequiredFieldValidatorInitialValue.aspx</title></head> <body> <form Runat="Server"> Comments: <br> <asp:TextBox id="txtComments" TextMode="MultiLine" Text="Enter Some Text" Runat="Server"/> <asp:RequiredFieldValidator ControlToValidate="txtComments" Text="You must enter some comments!" InitialValue="Enter Some Text" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> When the form in Listing 3.3 is first requested, the text Enter Some Text appears in the TextBox control. If you attempt to submit the form without changing this value, an error is displayed. Validating Expressions: The RegularExpressionValidator ControlYou can use RegularExpressionValidator to match the value entered into a form field to a regular expression. You can use this control to check whether a user has entered, for example, a valid e-mail address, telephone number, or username or password. Samples of how to use a regular expression to perform all these validation tasks are provided in the following sections. The properties and methods of this control are listed in Table 3.2. Table 3.2 RegularExpressionValidator Properties, Methods, and Events
You assign the regular expression that you want to use when performing validation to the ValidationExpression property. You can perform complex types of validation by using the correct regular expression.
You can submit the form in Listing 3.4, for example, only if you enter a product code that starts with the uppercase letter P and contains no more, or no fewer, than four numerals in a row. The RegularExpressionValidator control uses the regular expression P[0-9]{4}. Listing 3.4 RegularExpressionValidator.aspx<Script Runat="Server">
Sub Button_Click( s As Object, e As EventArgs )
If IsValid Then
Response.Redirect( "ThankYou.aspx" )
End If
End Sub
</Script>
<html>
<head><title>RegularExpressionValidator.aspx</title></head>
<body>
<form Runat="Server">
Product Code:
<br>
<asp:TextBox
id="txtProductCode"
Runat="Server"/>
<asp:RegularExpressionValidator
ControlToValidate="txtProductCode"
Text="Invalid Product Code!"
ValidationExpression="P[0-9]{4}"
Runat="Server" />
<p>
<asp:Button
Text="Submit"
OnClick="Button_Click"
Runat="Server"/>
</form>
</body>
</html>
If you experiment with the page contained in Listing 3.4, you'll quickly discover that you can submit the form without entering any text into the text box. The RegularExpressionValidator control does not require a value. The only way to require a value is to combine RegularExpressionValidator with RequiredFieldValidator. Nothing prevents you from associating multiple Validator controls with the same control. Validating E-Mail AddressesOne of the most common and difficult validation tasks that arise when performing form validation is validating an e-mail address. This task is actually much more difficult than you might assume because the e-mail standard is so complicated.
Even if a perfect e-mail validation regular expression is beyond your grasp, however, you can still hope to validate simple e-mail addresses. For example, you can use the following regular expression to check that an e-mail address starts with one or more nonwhitespace characters, followed by an @ sign, followed by one or more nonwhitespace characters, followed by a period, followed by one or more nonwhitespace characters: \S+@\S+\.\S+ So, this regular expression would match the following e-mail addresses: steve@somewhere.com steve@host.somewhere.com steve_smith@somewhere.com However, it would fail to match e-mail addresses like steve@aol steve smith@aol which is what you want. If you want to exclude all e-mail addresses that do not end with a top-level domain name between two and three characterssuch as .com, .net, and .wsyou would use this expression: \S+@\S+\.\S{2,3}
The page in Listing 3.5 demonstrates how you would use this regular expression with the RegularExpressionValidator control. Listing 3.5 RegularExpressionValidatorEmail.aspx<Script Runat="Server">
Sub Button_Click( s As Object, e As EventArgs )
If IsValid Then
Response.Redirect( "ThankYou.aspx" )
End If
End Sub
</Script>
<html>
<head><title>RegularExpressionvalidatorEmail.aspx</title></head>
<body>
<form Runat="Server">
Email Address:
<br>
<asp:TextBox
id="txtEmail"
Columns="50"
Runat="Server"/>
<asp:RegularExpressionValidator
ControlToValidate="txtEmail"
Text="Invalid Email Address!"
ValidationExpression="\S+@\S+\.\S{2,3}"
Runat="Server" />
<p>
<asp:Button
Text="Submit"
OnClick="Button_Click"
Runat="Server"/>
</form>
</body>
</html>
Validating Usernames and PasswordsTypically, Web sites require you to enter a username and password containing only alphanumeric characters or the underscore character. You can perform this type of validation using a regular expression that looks like this: \w+ This regular expression matches any expression that contains one or more word characters (a word character can be a letter, number, or the underscore character). You also can specify a minimum and maximum length for a password by using a regular expression that looks like this: \w{8,20}
This regular expression matches only expressions that are between 8 and 20 characters long. Finally, some Web sites require you to use at least one number and one letter in your password. You can use the following regular expression to satisfy this requirement: [a-zA-Z]+\w*\d+\w* This regular expression requires you to enter at least one letter, followed by any number of word characters, followed by at least one number, followed by any number of word characters. Listing 3.6 demonstrates how you can combine two RegularExpressionValidator controls and a RequiredFieldValidator control to validate a password. The Validation controls require you to enter a password that starts with at least one letter and contains one number and between 3 and 20 characters (special characters, such as # and ?, are not allowed). Listing 3.6 RegularExpressionValidatorPassword.aspx<Script Runat="Server">
Sub Button_Click( s As Object, e As EventArgs )
If IsValid Then
Response.Redirect( "thankyou.aspx" )
End If
End Sub
</Script>
<html>
<head><title>RegularExpressionValidatorPassowrd.aspx</title></head>
<body>
<form Runat="Server">
Password:
<br>
<asp:TextBox
id="txtPassword"
Columns="30"
Runat="Server"/>
<asp:RequiredFieldValidator
ControlToValidate="txtPassword"
Display="Dynamic"
Text="You must enter a password!"
Runat="Server" />
<asp:RegularExpressionValidator
ControlToValidate="txtPassword"
Display="Dynamic"
Text="Your password must contain between 3 and 20 characters!"
ValidationExpression="\w{3,20}"
Runat="Server" />
<asp:RegularExpressionValidator
ControlToValidate="txtPassword"
Display="Dynamic"
Text="Your password must contain at least one number and letter!"
ValidationExpression="[a-zA-Z]+\w*\d+\w*"
Runat="Server" />
<p>
<asp:Button
Text="Submit"
OnClick="Button_Click"
Runat="Server"/>
</form>
</body>
</html>
Validating Phone NumbersPhone numbers are difficult to validateespecially when you take into consideration foreign area codes and phone number extensions. Even if you ignore these problems and concentrate on U.S. phone numbers without extensions, many different formats still are used when entering a phone number. For example, the following formats are all commonly used: (555) 555-5555 555.555.5555 555 555-555 You can create a regular expression that matches all three of the preceding expressions, as follows: \(?\s*\d{3}\s*[\)\.\-]?\s*\d{3}\s*[\-\.]?\s*\d{4}
The page in Listing 3.7 illustrates how you can use this regular expression with RegularExpressionValidator. Listing 3.7 RegularExpressionValidatorPhone.aspx<Script Runat="Server">
Sub Button_Click( s As Object, e As EventArgs )
If IsValid Then
Response.Redirect( "ThankYou.aspx" )
End If
End Sub
</Script>
<html>
<head><title>RegularExpressionValidatorPhone.aspx</title></head>
<body>
<form Runat="Server">
Phone Number:
<br>
<asp:TextBox
id="txtPhone"
Columns="30"
Runat="Server"/>
<asp:RegularExpressionValidator
ControlToValidate="txtPhone"
Display="Dynamic"
Text="Invalid Phone Number!"
ValidationExpression="\(?\s*\d{3}\s*[\)\.\-]?\s*\d{3}\s*[\-\.]?\s*\d{4}"
Runat="Server" />
<p>
<asp:Button
Text="Submit"
OnClick="Button_Click"
Runat="Server"/>
</form>
</body>
</html>
Validating Web AddressesYou also might need to validate URLs that users enter into a form at your Web site. For example, you might have a registration form that contains a field for the URL of a user's home page. You can use the following regular expression to check for a valid URL: http://\S+\.\S+ This regular expression matches any string that begins with the characters http:// followed by one or more nonwhitespace characters, followed by a period, followed by one or more nonwhitespace characters. The page in Listing 3.8 demonstrates how you can use this regular expression with RegularExpressionValidator. Listing 3.8 RegularExpressionWeb.aspx<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) If IsValid Then Response.Redirect( "thankyou.aspx" ) End If End Sub </Script> <html> <head><title>RegularExpressionValidatorWeb.aspx</title></head> <body> <form Runat="Server"> Enter the address of your homepage: <br> <asp:TextBox id="txtHomepage" Columns="50" Runat="Server"/> <asp:RegularExpressionValidator ControlToValidate="txtHomepage" Display="Dynamic" Text="Invalid URL!" ValidationExpression="http://\S+\.\S+" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> One problem with the code in Listing 3.8 concerns case-sensitivity. The RegularExpressionValidator control uses case-sensitive comparisons. So, the regular expression discussed in this section matches http://www.superexpert.combut does not match Http://www.superexpert.comUnfortunately, RegularExpressionValidator does not have a property that you can set to enable regular expression options such as the i option (an option which enables case-insensitive matches). You cannot use the i option inline because the syntax for doing so with JavaScript is different from the syntax for doing so with the .NET classes. A not completely satisfactory workaround to this problem is illustrated by the page in Listing 3.9. The RegularExpressionValidator in this page performs a case insensitive match by using the i option. Furthermore, the RegularExpressionValidator disables client-side validation to prevent conflicts with JavaScript. This is not a perfect workaround to the problem since the page must be submitted back to the server before the RegularExpressionValidator will validate the expression. Listing 3.9 RegularExpressionIgnoreCase.aspx<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) If IsValid Then Response.Redirect( "thankyou.aspx" ) End If End Sub </Script> <html> <head><title>RegularExpressionValidatorIgnoreCase.aspx</title></head> <body> <form Runat="Server"> Enter the address of your homepage: <br> <asp:TextBox id="txtHomepage" Columns="50" Runat="Server"/> <asp:RegularExpressionValidator ControlToValidate="txtHomepage" Display="Dynamic" Text="Invalid URL!" EnableClientScript="False" ValidationExpression="(?i:http://\S+\.\S+)" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> Checking for Entry LengthYou also can use RegularExpressionValidator to check whether a form field contains more than a certain number of characters. This type of validation is especially useful when you're working with MultiLine TextBox controls. Because a MultiLine TextBox control does not have a MaxLength property, there is nothing to prevent a user from typing any number of characters in the text box. To check for a certain entry length, use regular expression quantifiers like this: .{0,10}
This expression matches any entry (including spaces) that contains between 0 and 10 characters. If you want to restrict the entry to a string of nonwhitespace characters that has a certain length, you would use a regular expression that looks like this: \S{0,10}
The page in Listing 3.10 demonstrates how you can use this regular expression with RegularExpressionValidator. Listing 3.10 RegularExpressionValidatorLength.aspx<Script Runat="Server">
Sub Button_Click( s As Object, e As EventArgs )
If IsValid Then
Response.Redirect( "ThankYou.aspx" )
End If
End Sub
</Script>
<html>
<head><title>RegularExpressionValidatorLength.aspx</title></head>
<body>
<form Runat="Server">
Enter your last name:
<br>(no more than 10 characters)
<br>
<asp:TextBox
id="txtLastname"
Columns="50"
Runat="Server"/>
<asp:RegularExpressionValidator
ControlToValidate="txtLastname"
Display="Dynamic"
Text="Your last name can contain
a maximum of 10 characters and no spaces!"
ValidationExpression="\S{0,10}"
Runat="Server" />
<p>
<asp:Button
Text="Submit"
OnClick="Button_Click"
Runat="Server"/>
</form>
</body>
</html>
Validating ZIP CodesYou also can use the RegularExpressionValidator control to validate ZIP codes. For example, if you want to require that a ZIP code entered into a form field contains exactly five digits, you would use the following regular expression: \d{5}
This expression matches strings that have no more or no fewer than five digits. The page in Listing 3.11 demonstrates how you would use this regular expression with the RegularExpressionValidator control. Listing 3.11 RegularExpressionValidatorZip.aspx<Script Runat="Server">
Sub Button_Click( s As Object, e As EventArgs )
If IsValid Then
Response.Redirect( "ThankYou.aspx" )
End If
End Sub
</Script>
<html>
<head><title>RegularExpressionValidatorZip.aspx</title></head>
<body>
<form Runat="Server">
ZIP Code:
<asp:TextBox
id="txtZipCode"
Columns="8"
Runat="Server"/>
<asp:RegularExpressionValidator
ControlToValidate="txtZipCode"
Display="Dynamic"
Text="Invalid ZIP Code!"
ValidationExpression="\d{5}"
Runat="Server" />
<p>
<asp:Button
Text="Submit"
OnClick="Button_Click"
Runat="Server"/>
</form>
</body>
</html>
Comparing Values: The CompareValidator ControlThe CompareValidator control performs comparisons between the data entered into a form field and another value. The other value can be a fixed value, such as a particular number, or a value entered into another control. All the properties and methods of the CompareValidator are listed in Table 3.3. Table 3.3 CompareValidator Properties, Methods, and Events
|