Section 8.5. Regular Expressions

8.5. Regular Expressions

Often, a simple value or range check is insufficient; you must check that the form of the data entered is correct. For example, you may need to ensure that a Zip Code is five digits, an email address is in the form name @place.com, a credit card matches the right format, and so forth.

A regular expression validator allows you to validate that a text field matches a regular expression . Regular expressions are a language for describing and manipulating text.

For complete coverage of regular expressions , see Mastering Regular Expressions , Second Edition, by Jeffrey Friedl (O'Reilly).


A regular expression consists of two types of characters : literals and metacharacters . A literal is a character you wish to match in the target string. A metacharacter is a special symbol that acts as a command to the regular expression parser. (The parser is the engine responsible for understanding the regular expression.) Consider this regular expression:

 ^\d{5}$ 

This will match any string that has five numerals. The initial metacharacter, ^ , indicates the beginning of the string. The second metacharacter, \d , indicates a digit. The third metacharacter, {5} , indicates five of the digits, and the final metacharacter, $ , indicates the end of the string. Thus, this regular expression matches five digits between the beginning and end of the line and nothing else.

When you use a RegularExpressionValidator control with client-side validation, the regular expressions are matched using JScript. This may differ in small details from the regular expression checking done on the server.


A more sophisticated algorithm might accept a five-digit Zip Code or a nine-digit Zip Code in the format of 12345-1234. Rather than using the \d metacharacter, you could designate the range of acceptable values:

 [0-9]{5}[0-9]{5}-[0-9]{4} 

Make a copy of the RangeValidator example named RegularExpressionValidator and replace the RangeValidator control with a RegularExpressionValidator control. Use the Properties window to set the ControlToValidate to txtValue and set the text to "Please enter a valid U. S. zip code." Finally, click on the property for Validation Expression, and click on the ellipsis. A Regular Expression Editor pops up with a few common regular expressions, or you can enter your own. Scroll down and choose U.S. ZIP Code, as shown in Figure 8-6.

Figure 8-6. Regular Expression Editor

If you choose "Custom," the validation expression will be left blank and you can enter any expression you choose. For help with creating custom regular expressions, we recommend the program RegEx Buddy (http://www.RegExBuddy.com).




Programming ASP. NET
Programming ASP.NET 3.5
ISBN: 0596529562
EAN: 2147483647
Year: 2003
Pages: 173

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