Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check user input date

So, a user can input a birth date by typing it or using a date picker. This could allow mistakes, so on the server side I'd like to check if it's a valid date.

I read a lot on strtotime() and saw a lot of examples, but not a 100% correct one.

This is what I have:

$geboortedatum = $_POST['geboortedatum'];
$geboortedatum = date("Y-m-d", strtotime($geboortedatum));
list($y, $m, $d) = explode("-", $geboortedatum);

// var_dump(checkdate($d,$m,$y));
if(checkdate($d, $m, $y)) {
    echo "OK Date";
}
else {
    echo "BAD Date";
    exit();
}

This works most of the time. Is there any solid method to check if the input is a real and correct date?

// EDIT

That was not a good example! It also doesn't work when the user inputs 31-31-1980. This is also valid, although it shouldn't be!

like image 985
Nick Avatar asked Mar 18 '26 10:03

Nick


2 Answers

You can use a combination of strtotime() and checkdate() to see if the date is valid:

function isRealDate($date) { 
    if (false === strtotime($date)) { 
        return false;
    } 
    list($year, $month, $day) = explode('-', $date); 
    return checkdate($month, $day, $year);
}

usage

if (isRealDate($geboortedatum)) {
    // date is ok
}
else {
    // date is not ok
}
like image 160
John Conde Avatar answered Mar 20 '26 22:03

John Conde


With DateTime you can make the shortest date&time validator for all formats.

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false
var_dump(validateDate(14, 'H')); # true
var_dump(validateDate('14', 'H')); # true

var_dump(validateDate('2012-02-28T12:12:12+02:00', 'Y-m-d\TH:i:sP')); # true
# or
var_dump(validateDate('2012-02-28T12:12:12+02:00', DateTime::ATOM)); # true

var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); # true
# or
var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', DateTime::RSS)); # true
var_dump(validateDate('Tue, 27 Feb 2012 12:12:12 +0200', DateTime::RSS)); # falsede here

function was copied from this answer or php.net

like image 22
Sargis Isoyan Avatar answered Mar 20 '26 22:03

Sargis Isoyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!