Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CodingRanger's avatar

Laravel date and time validation

I'm trying to make a simple form with pickup/delivery HTML 5 date fields.

It will have two date/time fields one for pickup and one for delivery

I want to validate that the pickup date is today or after today The time is set within the pickup window of let's say 5pm - 10pm and throw an error if that form is sent less than 30 minutes before A pickup with the date of today.

And with the delivery date, I want to make sure it's after the pickup date Next, to that, I also want to make sure the time and date is at least 24 hours after the pickup.

I know it sounds like a lot, I hope anyone got any tips on how to start writing this validation, I'm still really new to Laravel maybe I need to do this in Javascript?

0 likes
3 replies
Cronix's avatar
Cronix
Best Answer
Level 67

Due to the complexity of the rules, I'd probably go for a closure-based approach. You can get pretty fine grained with the error messages for each step of the way.

$validator = Validator::make($request->all(), [
    'pickup_date' => [
        'required',
        'date_format:"Y-m-d H:i:s"',
        function($attribute, $value, $fail) {
            $pickupDate = Carbon::parse($value);

            // is date < now?
            if ($pickupDate->lt(now()) {
                return $fail($attribute.' must be on or after ' . now()->toDateTimeString());
            }

            // is time between 5pm and 9:30pm? (Can you pickup 7 days/week?)
            $pickupTime = Carbon::createFromTime($pickupDate->hour, $pickupDate->minute, $pickupDate->second);
            $earliestTime = Carbon::createFromTimeString('17:00:00');
            $latestTime = Carbon::createFromTimeString('21:30:00');

            if ( ! $pickupTime->between($earliestTime, $latestTime)) {
                return $fail($attribute.' must be between 5pm and 9:30pm');
            }
        },
    ],
]);

I'm not saying that's the exact code to use, or the most efficient, but I'm just using carbon to compare dates/times and setting error messages for each. Anyway, hope that gives you something to go on.

https://laravel.com/docs/5.6/validation#using-closures

2 likes
pardeepkumar's avatar
public function rules()
{
    $this->prepInput();
    return [
        'appointment' => 'date_format:Y-m-d H:i:s'
    ];
}
Then in your view:

@if ($errors->has('appointment'))
    {{ $errors->first('appointment') }}
@endif 

Please or to participate in this conversation.