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

Tip

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.

Tip

When you use a RegularExpressionValidator control with client-side validation, the regular expressions are matched using ...

Get Programming ASP.NET, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.