Laravel 5.3 date validator: equal to or after start_date

PhpLaravelValidationLaravel 5.3

Php Problem Overview


I'm using Laravel 5.3 to validate start_date and end_date for an event. end_date should be equal to start_date or the after date. end_date >= start_date

$validator = Validator::make($data, [
    'start_date' 	=> 'required|date',
    'end_date' 		=> 'required|date|after:start_date',
]);

I tried to use after, but it only works for end_date > start_date. Of course, I can add custom rule using Validator::extend, but I'd like to know if we can do without adding custom rule.

Is there any way to add negative rule or add >= rule?

Thanks

Php Solutions


Solution 1 - Php

$validator = Validator::make($data, [
    'start_date'    => 'required|date',
    'end_date'      => 'required|date|after_or_equal:start_date',
]);

Use after_or_equal

Solution 2 - Php

Be careful when you set a validation rule after_or_equal:now and date_format with a format without hours, minutes or seconds!

For example:

$validationRules = [
    'my_time_start' => [
        'date_format:Y-m-d',// format without hours, minutes and seconds.
        'after_or_equal:now'
    ]
];

Laravel passing all date fields into the strtotime() function. Including now string. And strtotime('now') will return a unix timestamp with current minutes, hours and seconds.

For example, the today date is 2020-05-03. When you send a date value 2020-05-03 into your script, Laravel will pass 2 values into the strtotime() for compare:

strtotime('2020-05-03'); // always 1588489200
strtotime('now'); // NOT PREVIOUS VALUE, a different value each second, timestamp including current minutes, hour and seconds.

And you will always fail a validation (exclude a 1 second of the day).

To fix it, you should use:

$validationRules = [
    'my_time_start' => [
        'date_format:Y-m-d',// format without hours, minutes and seconds.
        'after_or_equal:' . date('Y-m-d'), // not 'now' string
    ]
];

Solution 3 - Php

upgarate to 5.4 and you can use after_or_equal see https://laravel.com/docs/5.4/validation#rule-after-or-equal

Solution 4 - Php

Actually, you can also use after_or_equal and before_or_equal when using at least Laravel version 5.3.31. This may help to avoid having to upgrade to a higher Laravel version.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul Z.View Question on Stackoverflow
Solution 1 - PhpSujiraj RView Answer on Stackoverflow
Solution 2 - PhpJames BondView Answer on Stackoverflow
Solution 3 - PhpFoued MOUSSIView Answer on Stackoverflow
Solution 4 - PhplowerendsView Answer on Stackoverflow