Reputation: 371
I have been using the date_parse method for input validation, which seems to be just fine... except it's not actually validating the date for correctness.
For example:
date_parse("2010/9/31/"); // returns FALSE
date_parse("2010-9-31"); // should return FALSE!
How can I get it to validate that 2010-9-31 is, in fact, an invalid date?
Upvotes: 2
Views: 378
Reputation: 133
$d = date_parse("2010-9-31");
if(count($d["warnings"]) > 0) {
echo array_shift($d["warnings"]) . "\n";
}
// --> "The parsed date was invalid"
Upvotes: 0
Reputation: 82078
To be clear, 2010-9-31
is a valid date, so the return you're getting is correct behavior.
If you're trying to force a specific format, you may want to use date_parse_from_format
print_r(date_parse_from_format("Y.n.j", $date));
Or, if that isn't sufficient, use preg_match
on $date before parsing it. If you do decide to use preg_match, you may want to ask a second question.
Upvotes: 1
Reputation: 11859
<?php
function is_date( $str )
{
$stamp = strtotime( $str );
if (!is_numeric($stamp))
{
return FALSE;
}
$month = date( 'm', $stamp );
$day = date( 'd', $stamp );
$year = date( 'Y', $stamp );
if (checkdate($month, $day, $year))
{
return TRUE;
}
return FALSE;
}
?>
source: http://php.net/manual/en/function.checkdate.php
Upvotes: 3