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
more complete coverage of this topic, please see MasteringRegularExpressions
by
Jeffrey Friedl (O’Reilly).
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 5 numerals. The initial
metacharacter, ^
, indicates the beginning of the
string. The second metacharacter, \d
, indicates a
digit. The third metacharacter, {5}
, indicates
exactly 5 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.
Note
A slightly more sophisticated algorithm might accept either a 5 digit zip code or a 9 digit (plus 4) zip code in the format ...
Get Programming ASP .NET 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.