I get dates from a text area in the dd-mm-yyyy or dd/mm/yyyy format (the user is allowed to use - or /) How do I check (using a regex or php) if the date is valid? Is there a regex or php method done this far to validate dates in this format? I tried searching here but could not find anything.
$date = str_replace("/", "-", $incoming);
$d = explode("-" , $date);
Re-assemble the parts and then run it through checkdate
if( !checkdate($d[1], $d[0], $d[2]) )
echo 'Not a recognised date' ;
http://www.php.net/manual/en/function.checkdate.php
I came up with this little function, it checks you use the format DD(separator)MM(sameseparator)YYYY
With DD, MM and YYYY as integers.
function valid_date($input_date) {
if(!preg_match('/(?P<d>\d{2})(?P<sep>\D)(?P<m>\d{2})\2(?P<y>\d{4})/',$input_date, $aux_date))
return false;
$aux = mktime(0,0,0,$aux_date['m'],$aux_date['d'],$aux_date['y']);
return $input_date == date('d'.$aux_date['sep'].'m'.$aux_date['sep'].'Y',$aux);
}
(Edited as sugested below)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With