Database Reference
In-Depth Information
Discussion
Pattern matching may not be sufficient for date or time checking. For example, a value
like 1947-15-19 might match a date pattern, but it's not a legal date. To perform more
rigorous value testing, combine pattern matching with range checking. Break out the
year, month, and day values, then check whether each is within the proper range. Years
should be less than 9999 (MySQL represents dates to an upper limit of 9999-12-31 ),
month values must be in the range from 1 to 12, and days must be in the range from 1
to the number of days in the month. That last part is the trickiest: it's month-dependent,
and also year-dependent for February because it changes for leap years.
Suppose that you're checking input dates in ISO format. In Recipe 12.6 , we used the
is_iso_date() function from the Cookbook_Utils.pm library file to perform a pattern
match on a date string and break it into component values. is_iso_date() returns
undef if the value doesn't satisfy a pattern that matches ISO date format. Otherwise, it
returns a reference to an array containing the year, month, and day values. The Cook‐
book_Utils.pm file also contains is_mmddyy_date() and is_ddmmyy_date() routines
that match dates in US or British format and return undef or a reference to an array of
date parts. (The parts returned are always in year, month, day order, not the order in
which the parts appear in the input date string.)
To perform additional checking on the result returned by any of those routines (as‐
suming that the result is not undef ), pass the date parts to is_valid_date() , another
library function:
$valid = is_valid_date ( $ref -> [ 0 ], $ref -> [ 1 ], $ref -> [ 2 ]);
Or, more concisely:
$valid = is_valid_date ( @ { $ref });
is_valid_date() returns nonzero if the date is valid, 0 otherwise. It checks the parts
of a date like this:
sub is_valid_date
{
my ( $year , $month , $day ) = @_ ;
# year must be nonnegative, month and day must be positive
return 0 if $year < 0 || $month < 1 || $day < 1 ;
# check maximum limits on individual parts
return 0 if $year > 9999
|| $month > 12
|| $day > days_in_month ( $year , $month );
return 1 ;
}
is_valid_date() requires separate year, month, and day values, not a date string. This
requires that you break candidate values into components before invoking it, but makes
Search WWH ::




Custom Search