Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date validation dd-mm-yyyy or dd/mm/yyyy

Tags:

regex

php

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.

like image 525
Norman Avatar asked Nov 27 '25 15:11

Norman


2 Answers

$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

like image 108
Cups Avatar answered Nov 29 '25 03:11

Cups


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)

like image 40
Adri V. Avatar answered Nov 29 '25 04:11

Adri V.