Using the RegularExpressionValidator ControlThe 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
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. |