0

Is it possible to validate and compare between 2 time inputs using the available rules, or I will have to have custom rule in this case?

I have 2 time inputs - start and end. They are in the format HH:mm and I need the end date to be greater than the start date.

Is there a combination I can have with the available rules to do that, or I should just create a custom rule?

pileup
  • 1
  • 2
  • 18
  • 45

1 Answers1

1

You can validate with laravel validators:

$this->validate($request, [
    'time_start' => 'date_format:H:i',
    'time_end' => 'date_format:H:i|after:time_start',
]);

Note: date_format only validates times in 24 hours format at maximum. If you have to validate more than 24 hours you have yo use a custom regex validation.

Links to Laravel documentation:

pileup
  • 1
  • 2
  • 18
  • 45
Voxxii
  • 369
  • 2
  • 9
  • Do you have any idea why it says my time is not matching the format? I tried both `HH:MM` and `HH:mm`, when I dd the `$request->start_time` for example, the string is `"11:22"` yet it does not match – pileup Aug 03 '23 at 11:31
  • 1
    The correct format is `H:i` – Vincent Decaux Aug 03 '23 at 11:40
  • @VincentDecaux thanks, it works! Do you know why though? Because Laravel docs link to Date Format, which in turn have link for the Time Formats: https://www.php.net/manual/en/datetime.formats.time.php. There I saw `HH:mm` – pileup Aug 03 '23 at 11:41
  • 1
    @Stackerito Laravel valides dateTime and not times, you should use the Php date formats, not time formats: https://www.php.net/manual/en/datetime.format.php – Vincent Decaux Aug 03 '23 at 19:14