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 RegularExpressionValidator 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 just 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 exactly five numerals. The initial metacharacter, ^, indicates the beginning of the string. The second metacharacter, \d, indicates a digit. The third metacharacter, {5}, indicates exactly 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 slightly more sophisticated algorithm might accept either a five-digit ZIP code or a nine-digit (plus four) ZIP code in the format of 12345-1234. Rather than using the \d metacharacter, you can simply designate the range of acceptable values: ValidationExpression="[0-9]{5}|[0-9]{5}-[0-9]{4}" To see this at work, add a new row to your form (below the second password row), as shown in Figure 9-21. Figure 9-21. Zip Code rowThe middle column consists of a textbox control (txtZip) and the third column has a RegularExpressionValidator . Set its attributes as shown in Table 9-8.
With this validator, your ZIP code is checked against the regular expression. Build and run the application again. If you enter a zip code in an invalid format, then the validation fails, and you see the message shown in Figure 9-22. Figure 9-22. Regular expression validation
|