Vincent Desrosiers
Vincent Desrosiers

Reputation: 170

PHP something wrong with my date validation

I'm trying to validate a date in an input type="date" in d-m-Y format. The date cannot be higher than today. I'm converting the difference in numbers and then ask if the number is less than 0.

Here's my validation function:

public static function validateDate($date){
    $dateToday = date_create(date('d-m-Y'));
    $datetime = date_create($date);
    if(date_diff($dateToday, $datetime)->format('%a') < 0){
        return false;
    }
    else{
        return true;
    }
}

The function doesn't work. the user can choose any date in the future and it goes right into the DB as YYYY-MM-DD.

I'm pretty lost here any help would be greatly appreciated.

Upvotes: 0

Views: 95

Answers (1)

S. Imp
S. Imp

Reputation: 2895

For starters, this is probably a bad move:

$dateToday = date_create(date('d-m-Y'));

It's bad because both date and month have 2 digits. While it may actually give you the result you expect, it looks counterintuitive to U.S. coders because dates are typcially written m-d-Y here. I would suggest date("F j, Y") which is a much clearer date format: var_dump(date("F j, Y")); // outputs "December 8, 2018" Second, you don't appear to do any validation on the $date parameter supplied to your function. It is presumably a string in d-m-Y format and you should enforce that with some validation.

Lastly, you the %a formatter you specify in this line just provides the digits of the date difference...it doesn't specify whether that is a positive difference or a negative difference.:

if(date_diff($dateToday, $datetime)->format('%a') < 0){
    //blah blah blah
}

You would need to include the %R format flag too to get the +/- of the difference:

if(date_diff($dateToday, $datetime)->format('%R%a') < 0){
    //blah blah blah
}

And finally, as of PHP 5.2.2., you can just compare the date objects created using a comparison operator. This is better than your code which compares a string to zero. Try this function:

public static function validateDate($date){
    if (!preg_match('/^\d{2}-\d{2}-\d{4}$/', $date)) {
            throw new Exception("$date is not a valid date in d-m-Y format");
    }
    $today = date_create(date("Y-m-d"));
    $datetime = date_create($date);

    if ($datetime > $today) {
            return false;
    } else {
            return true;
    }
}

Upvotes: 1

Related Questions