- Using Client-side Validation
- Requiring Fields: The RequiredFieldValidator Control
- Validating Expressions: The RegularExpressionValidator Control
- Comparing Values: The CompareValidator Control
- Checking for a Range of Values: The RangeValidator Control
- Summarizing Errors: The ValidationSummary Control
- Performing Custom Validation: The CustomValidator Control
- Disabling Validation
- Summary
Validating Expressions: The RegularExpressionValidator Control
You 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
Properties |
Description |
ControlToValidate |
Specifies the id of the control that you want to validate. |
Display |
Sets how the error message contained in the Text property is displayed. Possible values are Static, Dynamic, and None; the default value is Static. |
EnableClientScript |
Enables or disables client-side form validation. This property has the value True by default. |
Enabled |
Enables or disables both server and client-side validation. This property has the value True by default. |
ErrorMessage |
Specifies the error message that is displayed in the ValidationSummary control. This error message is displayed by the control when the Text property is not set. |
IsValid |
Has the value True when the validation check succeeds and False otherwise. |
Text |
Sets the error message displayed by the control. |
ValidationExpression |
Specifies the regular expression to use when performing validation. |
Methods |
Description |
Validate |
Performs validation and updates the IsValid property. |
Events |
Description |
None |
|
NOTE
Regular expressions are discussed in detail in Chapter 24, "Working with Collections and Strings."
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.
WARNING
Regular expressions work somewhat differently in JavaScript than they do in the .NET framework. So, in certain circumstances, the client-side validation code used for matching regular expressions might return different results than the server-side validation code. Even worse, a valid .NET regular expression might generate a JavaScript error. For example, the syntax for using regular expression options inlinesuch as the i optiondiffers between JavaScript and the .NET classes.
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 Addresses
One 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.
NOTE
You can find the specification for e-mail addresses in RFC 822, Standard for ARPA Internet Text Messages, at the following location:
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 Passwords
Typically, 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 Numbers
Phone 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 Addresses
You 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.com
but does not match
Http://www.superexpert.com
Unfortunately, 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 Length
You 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 Codes
You 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>