Tuesday, 28 February 2017

Date Format Validation in PHP

How can you validate date format in php using Regex and without Regex using simple php date function. If you are working on any application where right data format is mandatory then you must have to apply right data format validation on server side so that you can easily calculate taken duration for any task.


Date Format Validation in PHP



Going to validate this format YYYY-MM-DD

Date Format Validation 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



Date Format Validation 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

HTML APIs: What They Are And How To Design A Good One

As JavaScript developers, we regularly forget that not everybody has a similar data as USA. It’s referred to as the curse of knowledge:...