Skip to content

Instantly share code, notes, and snippets.

@daogurtsov
Created July 24, 2013 15:47
Show Gist options
  • Save daogurtsov/6071799 to your computer and use it in GitHub Desktop.
Save daogurtsov/6071799 to your computer and use it in GitHub Desktop.
/*Date validation, fixed regex for formats which use dash as separator: added $regexp = preg_replace('/(?<=(\]|\)))'.$separator.'(?=(\[|\())/i', "\\" . $separator, $regexp); to escape dash only between groups. Removed optional two digits year and one digit day or month to fit MySQL date format requirement */
function is_valid_date($value, $format = 'dd.mm.yyyy'){
if(strlen($value) >= 6 && strlen($format) == 10){
// find separator. Remove all other characters from $format
$separator_only = str_replace(array('m','d','y'),'', $format);
$separator = $separator_only[0]; // separator is first character
if($separator && strlen($separator_only) == 2){
// make regex
$regexp = str_replace('mm', '(0[1-9]|1[0-2])', $format);
$regexp = str_replace('dd', '(0[1-9]|[1-2][0-9]|3[0-1])', $regexp);
$regexp = str_replace('yyyy', '(19|20)[0-9][0-9]', $regexp);
$regexp = preg_replace('/(?<=(\]|\)))'.$separator.'(?=(\[|\())/i', "\\" . $separator, $regexp);
if($regexp != $value && preg_match('/'.$regexp.'\z/', $value)){
// check date
$arr=explode($separator,$value);
$day= intval($arr[2]);
$month= intval($arr[1]);
$year=intval($arr[0]);
return checkdate($month, $day, $year);
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment