How to ADD Date Format Validation in PHP
Using Regex
function validateDate($data) { if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]
|[1-2][0-9]|3[0-1])$/",$date)) { return true; }else{ return false; } } var_dump(validateDate("2017-02-27")) // true var_dump(validateDate("27-02-2017")) // false var_dump(validateDate("2017-14-27")) // false
Using PHP Date object
function validateDate($date) { $dt = DateTime::createFromFormat('Y-m-d', $date); return $dt && $dt->format('Y-m-d') === $date; } var_dump(validateDate("2017-02-27")) // true var_dump(validateDate("27-02-2017")) // false var_dump(validateDate("2017-14-27")) // false
No comments:
Post a Comment