Using the RegularExpressionValidator Control


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.


Listing 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  runat="server">     <title>Show RegularExpressionValidator</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  Text="Email Address:"         AssociatedControl         Runat="server" />     <asp:TextBox                  Runat="server" />     <asp:RegularExpressionValidator                  ControlToValidate="txtEmail"         Text="(Invalid email)"         ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"         Runat="server" />     <br /><br />     <asp:Button                  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.

Note

There are huge collections of regular expression patterns living on the Internet. The easiest way to find a good regular expression for a pattern is to simply Google it.


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.

Visual Web Developer Note

If you open the property sheet for a RegularExpressionValidator control in Design view and select the ValidationExpression property, you can view a number of canned regular expressions. Visual Web Developer includes regular expressions for patterns such as email addresses, phone numbers, and Social Security numbers.





ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net