Reputation: 195
I have a regex which validate birthday:
if(!preg_match('/^(0?[1-9]|1[012])[- .\/](0?[1-9]|[12][0-9]|3[01])[- .\/](19|20)?[0-9]{2}$/', $_POST['bday'])
{
echo 'enter your birthdate in a valid format. mm/dd/yyy';
}
which is:
correct month
leap year date is not accurate
february accepts day 30 & 31
and the year 20 accepts greater than 2013
I only done correct with months how can I do more accurate birthday validation? or there is any alternate way to validate birthday?
my desired output is:
validate leap year date on month of february
year must not greater than 2010
OUTPUT:
02/14/2010
I'm just quite new on regex kindly help?
Upvotes: 1
Views: 1594
Reputation: 76646
A regex isn't well-suited for parsing dates. PHP already has built-in functions and classes to do this and you should use that instead. Here's how this can be done using PHP's DateTime class (function by Glavić, from php.net):
function validateDate($date, $format = 'm/d/Y')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date && $d->format('Y') <= 2010;
}
For example:
var_dump(validateDate('02/14/2010')); // bool(true)
var_dump(validateDate('02/14/2011')); // bool(false)
Upvotes: 6