|
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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
You can use CompareValidator, for example, to check whether a user entered a number greater than 7, check to see whether a date entered into one control is greater than a date entered into another control, or check whether a currency amount is less than a certain specified amount. CompareValidator also can be used to check whether a form field contains a particular data type. For example, you can use the control to check whether a user entered a valid date, number, or currency value. Comparing the Value of One Control to the Value of AnotherImagine that you have two form fields for entering dates: one labeled Start Date and one labeled End Date. Now, imagine that you want to make sure that any date entered into the second form field is later than any date entered in the first form field. You can perform this type of form validation by using the CompareValidator control. To compare two dates, you need to set the ControlToValidate, ControlToCompare, Operator, and Type properties of the CompareValidator control. The page in Listing 3.12 illustrates how you can check whether one date is later than another. Listing 3.12 CompareValidator.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>CompareValidator.aspx</title></head> <body> <form Runat="Server"> Start Date: <asp:TextBox id="txtStartDate" Columns="8" Runat="Server"/> End Date: <asp:TextBox id="txtEndDate" Columns="8" Runat="Server"/> <br> <asp:CompareValidator ControlToValidate="txtEndDate" ControlToCompare="txtStartDate" Display="Dynamic" Text="End date must be greater than start date!" Operator="GreaterThan" Type="Date" Runat="Server" /> <p> <asp:Button Text="Submit!" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> The CompareValidator control in Listing 3.12 uses the ControlToValidate and ControlToCompare properties to indicate the controls to use for the comparison. The Operator property has the value GreaterThan. CompareValidator checks whether the value entered into the txtEndDate control is greater than the value entered into the txtStartDate control. Finally, the Type property has the value Date. The control compares the two values as date values rather than string or integer values. CompareValidator does not check whether values are actually entered into the controls that it is comparing. If either the txtStartDate or txtEndDate controls are left blank, the form passes the validation check. Comparing the Value of a Control to a Fixed ValueInstead of using CompareValidator to compare the values of two controls, you can use it to compare a value in one control to a fixed value. For example, suppose that you are building an auction Web site, and you want a user to enter a bid higher than a certain amount. You can use CompareValidator to compare a bid to the previous highest bid. The page in Listing 3.13 illustrates how you would do so. Listing 3.13 CompareValidatorValue.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>CompareValidatorValue.aspx</title></head> <body> <form Runat="Server"> Minimum Bid: $2,344.89 <br> Enter your bid: <asp:TextBox id="txtBidAmount" Columns="8" Runat="Server"/> <asp:CompareValidator ControlToValidate="txtBidAmount" ValueToCompare="2,344.89" Display="Dynamic" Text="Your bid must be greater than the minimum bid!" Operator="GreaterThan" Type="Currency" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> If the user attempts to enter a bid less than $2,344.89, an error message is displayed. The fixed value is assigned to CompareValidator by using its ValueToCompare property. Performing a Data Type CheckA common validation task involves performing data type checks. For example, you might need to check whether a user has entered a date in a date field, a string in a string field, or a number in a number field. You can perform this type of validation with the CompareValidator control by using the DataTypeCheck value of the Operator property. Imagine that you have a form field for a user's birth date. The page in Listing 3.14 illustrates how you can check for a valid date. Listing 3.14 CompareValidatorDataTypeCheck.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>CompareValidatorDataTypeCheck.aspx</title></head> <body> <form Runat="Server"> Enter your birth date: <asp:TextBox id="txtBirthDate" Columns="10" Runat="Server"/> <asp:CompareValidator ControlToValidate="txtBirthDate" Display="Dynamic" Text="Invalid birth date!" Operator="DataTypeCheck" Type="Date" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> In Listing 3.14, the CompareValidator control's Operator property is assigned the value DataTypeCheck, and the Type property is assigned the value Date. If an invalid date is entered into the txtBirthDate form field, the CompareValidator control displays an error.
Checking for a Range of Values: The RangeValidator ControlYou can use the RangeValidator control to check whether the value of a form field falls between a minimum and maximum value. The minimum and maximum values can be dates, numbers, currency amounts, or strings. All the properties and methods of this control are listed in Table 3.4. Table 3.4 RangeValidator Properties, Methods, and Events
You can use RangeValidator, for example, to check whether a form field contains a date that falls within a certain range. The page in Listing 3.15 checks whether the date entered is greater or equal to today's date, but less than three months in the future. Listing 3.15 RangeValidator.aspx<Script Runat="Server"> Sub Page_Load valgMeetingDate.MinimumValue = Now.Date valgMeetingDate.MaximumValue = Now.Date.AddMonths( 3 ) End Sub Sub Button_Click( s As Object, e As EventArgs ) If IsValid Then Response.Redirect( "ThankYou.aspx" ) End If End Sub </Script> <html> <head><title>RangeValidator.aspx</title></head> <body> <form Runat="Server"> Choose a meeting date in the next three months: <br> <asp:TextBox id="txtMeetingDate" Columns="10" Runat="Server"/> <asp:RangeValidator ID="valgMeetingDate" ControlToValidate="txtMeetingDate" Display="Dynamic" Text="Date must be in the next 3 months!" Type="Date" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> The Page_Load subroutine in Listing 3.15 assigns values to the MinimumValue and MaximumValue properties of the RangeValidator control. Today's date is assigned to the MinimumValue property, and a date three months in the future is assigned to the MaximumValue property. If you need to detect whether a value entered into a form field falls within a certain range determined by the values of other form fields, you should use the CompareValidator rather than the RangeValidator. The CompareValidator, unlike RangeValidator, enables you to compare the values of different controls. For example, the page in Listing 3.16 contains three TextBox controls. You must enter a number greater than or equal to the value entered into the first control, and less than or equal to the value entered into the last control; otherwise, you receive an error. Listing 3.16 CompareValidatorRange.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>CompareValidatorRange.aspx</title></head> <body> <form Runat="Server"> Minimum Value: <asp:TextBox id="txtMinNumber" Runat="Server"/> <p> Maximum Value: <asp:TextBox id="txtMaxNumber" Runat="Server"/> <p> Value: <asp:TextBox id="txtRangeNumber" Runat="Server"/> <asp:CompareValidator ControlToValidate="txtRangeNumber" ControlToCompare="txtMinNumber" Display="Dynamic" Text="Number must be greater than minimum value!" Operator="GreaterThan" Type="Integer" Runat="Server" /> <asp:CompareValidator ControlToValidate="txtRangeNumber" ControlToCompare="txtMaxNumber" Display="Dynamic" Text="Number must be less than maximum value!" Operator="LessThan" Type="Integer" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> Summarizing Errors: The ValidationSummary ControlImagine that you have a form with 50 form fields. If you use only the Validation controls discussed in the previous sections of this chapter to display errors, seeing an error message on the page might be difficult. For example, you might have to scroll down to the 48th form field to find the error message. Fortunately, Microsoft includes a ValidationSummary control with the Validation controls. You can use this control to summarize all the errors at the top of a page, or wherever else you wish. All the properties and methods of this control are listed in Table 3.5. Table 3.5 ValidationSummary Properties, Methods, and Events
The page in Listing 3.17 illustrates how you can use the ValidationSummary control to display a summary of errors (see Figure 3.3). Figure 3.3 Listing 3.17 ValidationSummary.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>ValidationSummary.aspx</title></head> <body> <form Runat="Server"> <asp:ValidationSummary HeaderText="There are problems with the following form fields:" Runat="Server" /> <p> First Name: <br> <asp:TextBox ID="txtFirstname" Runat="Server" /> <asp:RequiredFieldValidator ID="reqVal1" ControlToValidate="txtFirstname" Text="You must enter a first name!" ErrorMessage="First Name" Runat="Server" /> <p> Last Name: <br> <asp:TextBox ID="txtLastname" Runat="Server" /> <asp:RequiredFieldValidator ControlToValidate="txtLastname" Text="You must enter a last name!" ErrorMessage="Last Name" Runat="Server" /> <p> Occupation: <br> <asp:TextBox ID="txtOccupation" Runat="Server" /> <asp:RequiredFieldValidator Text="You must enter an occupation!" ControlToValidate="txtOccupation" ErrorMessage="Occupation" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> Notice how each Validation control is assigned an error message with the ErrorMessage property. These error messages are displayed in the ValidationSummary control whenever a problem occurs with a form field. Don't confuse the ErrorMessage and Text properties. Typically, you use the Text property of a Validation control to display an error message next to a form field, and you use the ErrorMessage property to display a message in the ValidationSummary control. By default, the ValidationSummary control displays error messages in a bulleted list. However, you also have the option of displaying the messages in a nonbulleted list or within a single paragraph. To control how the ValidationSummary control formats its summary of errors, modify its DisplayMode property. Figure 3.4 shows how the ValidationSummary control displays error messages with each of the different settings of the DisplayMode property. Figure 3.4 Displaying Pop-Up Error MessagesHave you ever seen those obnoxious pop-up error messages that some sites use to report validation errors? You can provide these messages for your users, too! You can enable the ValidationSummary control's ShowMessageBox property to display error messages in a dialog box. Listing 3.18 demonstrates how you can enable this property (see Figure 3.5 for the output).
Figure 3.5 Listing 3.18 ValidationSummaryPopUp.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>ValidationSummaryPopUp.aspx</title></head> <body> <form Runat="Server"> <asp:ValidationSummary ShowMessageBox="True" HeaderText="There are problems with the following form fields:" Runat="Server" /> <p> First Name: <br> <asp:TextBox ID="txtFirstname" Runat="Server" /> <asp:RequiredFieldValidator ControlToValidate="txtFirstname" Text="You must enter a first name!" ErrorMessage="First Name" Runat="Server" /> <p> Last Name: <br> <asp:TextBox ID="txtLastname" Runat="Server" /> <asp:RequiredFieldValidator ControlToValidate="txtLastname" Text="You must enter a last name!" ErrorMessage="Last Name" Runat="Server" /> <p> Occupation: <br> <asp:TextBox ID="txtOccupation" Runat="Server" /> <asp:RequiredFieldValidator Text="You must enter an occupation!" ControlToValidate="txtOccupation" ErrorMessage="Occupation" Runat="Server" /> <p> <asp:Button Text="Submit" OnClick="Button_Click" Runat="Server"/> </form> </body> </html> Performing Custom Validation: The CustomValidator ControlThe Validation controls included with ASP.NET enable you to handle a wide range of validation tasks. However, you cannot perform certain types of validation with the included controls. To handle any type of validation that is not covered by the standard validation controls, you need to use the CustomValidator control. All the properties, methods, and events of this control are listed in Table 3.6. Table 3.6 CustomValidator Properties, Methods, and Events
You cannot use any of the included Validation controls, for example, with information that is stored in a database table. Typically, you want users to enter a unique username and/or e-mail address when completing a registration form. To determine whether a user has entered a unique username or e-mail address, you must perform a database lookup. Using the CustomValidator control, you can write any subroutine for performing validation that you wish. The validation can be performed completely server-side. Alternatively, you can write a custom client-side validation function to use with the control. You can write the client-side script using either JavaScript or VBScript. To create the server-side validation routine, you'll need to create a Visual Basic subroutine that looks like this: Sub CustomValidator_ServerValidate( s As object, e As ServerValidateEventArgs ) End Sub This subroutine accepts a special ServerValidateEventArgs parameter that has the following two properties:
For this example, create a custom validation subroutine that checks for the string ASP.NET Unleashed. If you enter text into a TextBox control and it does not contain the name of this book, it fails the validation test. First, you need to create a server-side version of the validation subroutine: Sub CustomValidator_ServerValidate( s As Object, e As ServerValidateEventArgs ) Dim strValue As String strValue = e.Value.ToUpper() If strValue.IndexOf( "ASP.NET UNLEASHED" ) > -1 Then e.IsValid = True Else e.IsValid = False End If End Sub This subroutine checks whether the string ASP.NET Unleashed appears in the value of the control being validated. If it does, the value True is assigned to the IsValid property; otherwise, the value False is assigned. You could just implement custom validation with the server-side validation subroutine, which is all you need to get the CustomValidator control to work. However, if you want to get really fancy, you could implement it in a client-side script as well. Be fancy. This VBScript client-side script implements the validation subroutine: <Script Language="VBScript"> Sub CustomValidator_ClientValidate( s, e ) Dim strValue strValue = UCase( e.Value ) If Instr( strValue, "ASP.NET UNLEASHED" ) > 0 Then e.IsValid = True Else e.IsValid = False End If End Sub </Script> This subroutine performs exactly the same task as the previous server-side validation subroutine; however, it is written in VBScript rather than Visual Basic. After you create your server-side and client-side subroutines, you can hook them up to your CustomValidator control by using the OnServerValidate and ClientValidationFunction properties. The page in Listing 3.19 illustrates how you can use the custom validation subroutines you just built. Listing 3.19 CustomValidator.aspx<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs ) If IsValid Then Response.Redirect( "ThankYou.aspx" ) End If End Sub Sub CustomValidator_ServerValidate( s As Object, e As ServerValidateEventArgs ) Dim strValue As String strValue = e.Value.ToUpper() If strValue.IndexOf( "ASP.NET UNLEASHED" ) > -1 Then e.IsValid = True Else e.IsValid = False End If End Sub </script> <html> <head> <Script Language="VBScript"> Sub CustomValidator_ClientValidate( s, e ) Dim strValue strValue = UCase( e.Value ) If Instr( strValue, "ASP.NET UNLEASHED" ) > 0 Then e.IsValid = True Else e.IsValid = False End If End Sub </Script> <title>CustomValidator.aspx</title> </head> <body> <form Runat="Server"> Enter the name of your favorite book: <br> <asp:CustomValidator ControlToValidate="txtFavBook" ClientValidationFunction="CustomValidator_ClientValidate" OnServerValidate="CustomValidator_ServerValidate" Display="Dynamic" Text="You must type ASP.NET Unleashed!" Runat="Server" /> <br> <asp:TextBox ID="txtFavBook" TextMode="Multiline" Columns="50" Rows="3" Runat="Server" /> <p> <asp:Button Text="Submit!" OnClick="Button_Click" Runat="Server" /> </form> </body> </html> Validating Credit Card NumbersIn this section, you look at a slightly more complicated but more realistic application of the CustomValidator control. You learn how to write a custom validation function that checks whether a credit card number is valid. The function uses the Luhn algorithm xto check whether a credit card is valid. This function does not check whether credit is available in a person's credit card account. However, it does check whether a string of credit card numbers satisfies the Luhn algorithm, an algorithm that the numbers in all valid credit cards must satisfy. The page in Listing 3.20 contains a TextBox control that is validated by a CustomValidator. If you enter an invalid credit card number, the validation check fails and an error message is displayed.
Listing 3.20 CustomValidatorLuhn.aspx<Script Runat="Server"> Sub Button_Click( s As Object, e As EventArgs) If IsValid Then Response.Redirect( "Thankyou.aspx" ) End If End Sub Sub ValidateCCNumber( s As Object, e As ServerValidateEventArgs ) Dim intCounter As Integer Dim strCCNumber As String Dim blnIsEven As Boolean = False Dim strDigits As String = "" Dim intCheckSum As Integer = 0 ' Strip away everything except numerals For intCounter = 1 To Len( e.Value ) If IsNumeric( MID( e.Value, intCounter, 1 ) ) THEN strCCNumber = strCCNumber & MID( e.Value, intCounter, 1 ) End If Next ' If nothing left, then fail If Len( strCCNumber ) = 0 Then e.IsValid = False Else ' Double every other digit For intCounter = Len( strCCNumber ) To 1 Step -1 If blnIsEven Then strDigits = strDigits & cINT( MID( strCCNumber, intCounter, 1 ) ) * 2 Else strDigits = strDigits & cINT( MID( strCCNumber, intCounter, 1 ) ) End If blnIsEven = ( NOT blnIsEven ) Next ' Calculate CheckSum For intCounter = 1 To Len( strDigits ) intCheckSum = intCheckSum + cINT( MID( strDigits, intCounter, 1 ) ) Next ' Assign results e.IsValid = (( intCheckSum Mod 10 ) = 0 ) End If End Sub </script> <html> <head><title>CustomValidatorLuhn.aspx</title></head> <body> <form Runat="Server"> Enter your credit card number: <br> <asp:TextBox ID="txtCCNumber" Columns="20" MaxLength="20" Runat="Server" /> <asp:CustomValidator ControlToValidate="txtCCNumber" OnServerValidate="ValidateCCNumber" Display="Dynamic" Text="Invalid Credit Card Number!" Runat="Server" /> <p> <asp:Button Text="Submit!" OnClick="Button_Click" Runat="Server" /> </form> </body> </html> Disabling ValidationTypically, a form includes a Cancel button that enables you to stop working on the form and navigate to a new page. Implementing a Cancel button in a form that includes validation controls, however, is more difficult than you might expect. The problem is that the client-side validation scripts can prevent any subroutine associated with the Cancel button from ever executing. To get around this problem, you need to use a special property of the Button, LinkButton, and ImageButton controls named the CausesValidation property. You can use the CausesValidation property to enable or disable validation when a particular button is clicked. For example, the page in Listing 3.21 contains both a Submit and Cancel button. The CausesValidation property is assigned the value False in the case of the Cancel button. Listing 3.21 CausesValidation.aspx<Script runat="Server"> Sub btnSubmit_Click( s As Object, e As EventArgs ) If IsValid Then Response.Redirect( "ThankYou.aspx" ) End If End Sub Sub btnCancel_Click( s As Object, e As EventArgs ) Response.Redirect( "Cancel.aspx" ) End Sub </Script> <html> <head><title>CausesValidation.aspx</title></head> <body> <form runat="Server"> Enter your first name: <br> <asp:TextBox id="txtFirstName" Runat="Server" /> <asp:RequiredFieldValidator ControlToValidate="txtFirstName" Text="Required!" Runat="Server" /> <p> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="Server" /> <asp:Button id="btnCancel" Text="Cancel" OnClick="btnCancel_Click" CausesValidation="False" Runat="Server" /> </form> </body> </html> SummaryThis chapter covered all the ASP.NET validation controls. You learned how to make required form fields by using the RequiredFieldValidator control, how to perform complex pattern validation by using the RegularExpressionValidator control, how to compare values and data types by using the CompareValidator control, and how to check for a range of values by using the RangeValidator control. You also learned how to summarize validation errors by using the ValidationSummary control. You learned how to summarize errors within the page itself and how to display the summary in a pop-up dialog box. Finally, you learned how to implement custom server-side and client-side validation functions by using the CustomValidator control. You should now be ready to handle any conceivable Web site validation task. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Copyright © 2000-2003 ASPAlliance.com Page Rendered at
11/8/2009 1:00:07 AM |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||