Friday, November 20, 2009

Date Validation in php

To check that enter date is in valid format in php by using validCurrentDate() function


function validCurrentDate($date){
//replace / with - in the date
$date = strtr($date,'/','-');
//explode the date into date,month and year

$datearr = explode('-', $date);

//count that there are 3 elements in the array

if(count($datearr) == 3){
list($d, $m, $y) = $datearr;

/*checkdate - check whether the date is valid. strtotime - Parse about any English textual
datetime description into a Unix timestamp. Thus, it restricts any input before 1901 and after 2038, i.e., it invalidate outrange dates like 01-01-2500. preg_match - match the pattern*/

if(checkdate($m, $d, $y) && strtotime("$y-$m-$d") && preg_match('#\b\d{2}[/-]\d{2}[/-]\d{4}\b#', "$d-$m-$y"))
{
/*echo "valid date";*/
return TRUE;
}
else {
/*echo "invalid date";*/
return FALSE;
}
}
else {
/*echo "invalid date";*/
return FALSE;
}
/*echo "invalid date";*/
return FALSE;
}

?>

No comments:

Post a Comment