- Overview of the Validation Controls
- Using the RequiredFieldValidator Control
- Using the RangeValidator Control
- Using the CompareValidator Control
- Using the RegularExpressionValidator Control
- Using the CustomValidator Control
- Using the ValidationSummary Control
- Creating Custom Validation Controls
- Summary
Using the RegularExpressionValidator Control
The RegularExpressionValidator control enables you to compare the value of a form field against a regular expression. You can use a regular expression to represent string patterns such as email addresses, Social Security numbers, phone numbers, dates, currency amounts, and product codes.
For example, the page in Listing 3.13 enables you to validate an email address (see Figure 3.11).
Figure 3.11 Validating an email address.
Example 3.13. ShowRegularExpressionValidator.aspx
<%@ Page Language="VB" %> <!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 id="Head1" runat="server"> <title>Show RegularExpressionValidator</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblEmail" Text="Email Address:" AssociatedControlID="txtEmail" Runat="server" /> <asp:TextBox id="txtEmail" Runat="server" /> <asp:RegularExpressionValidator id="regEmail" ControlToValidate="txtEmail" Text="(Invalid email)" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </div> </form> </body> </html>
The regular expression is assigned to the RegularExpressionValidator control's ValidationExpression property. It looks like this:
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
Regular expressions are not fun to read. This pattern matches a simple email address. The \w expression represents any non-whitespace character. Therefore, roughly, this regular expression matches an email address that contains non-whitespace characters, followed by an @ sign, followed by non-whitespace characters, followed by a period, followed by more non-whitespace characters.
Just like the other validation controls, the RegularExpressionValidator doesn't validate a form field unless the form field contains a value. To make a form field required, you must associate a RequiredFieldValidator control with the form field.