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.
|
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.
|
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.
|