Database Reference
In-Depth Information
/^[- \d]+/
(Perl permits the \d digit specifier within character classes.) However, that pattern
doesn't identify values of the wrong length, and it may be useful to remove extra‐
neous characters before storing values in MySQL. To require credit card values to
contain 16 digits, use a substitution that removes all nondigits, then check the length
of the result:
$val =~ s/\D//g ;
$valid = ( length ( $val ) == 16 );
12.6. Using Patterns to Match Dates or Times
Problem
You must make sure a string looks like a date or time.
Solution
Use a pattern that matches the type of temporal value you expect. Be sure to consider
issues such as how strict to be about delimiters between subparts and the lengths of the
subparts.
Discussion
Dates are a validation headache because they come in so many formats. Pattern tests
are extremely useful for weeding out illegal values, but often insufficient for full verifi‐
cation: a date might have a number where you expect a month, but the date isn't valid
if the number is 13. This section introduces some patterns that match a few common
date formats. Recipe 12.11 revisits this topic in more detail and discusses combining
pattern tests with content verification.
To require values to be dates in ISO ( CCYY-MM-DD ) format, use this pattern:
/^\d{4}-\d{2}-\d{2}$/
The pattern requires the - character as the delimiter between date parts. To permit either
- or / as the delimiter, use a character class between the numeric parts (the slashes are
escaped with a backslash to prevent them from being interpreted as the end of the pattern
constructor):
/^\d{4}[-\/]\d{2}[-\/]\d{2}$/
To avoid the backslashes, use a different delimiter around the pattern:
m |^\ d { 4 }[ - /]\d{2}[-/ ] \ d { 2 } $|
To permit any nondigit delimiter (which corresponds to how MySQL operates when it
interprets strings as dates), use this pattern:
Search WWH ::




Custom Search