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

develop12's avatar

Validation Request - between:min,max

I would like to know if it is possible to validate that an input time is between two time limits, I have done the following based on several sites that I reviewed but I do not get a successful result.

'start_time' => 'required|date_format:H:i|between:09:00,18:00',

I would greatly appreciate your support.

0 likes
3 replies
Snapey's avatar

You can use a rule closure with bespoke logic

     'start_time' => [
       'required',
       function ($attribute, $value, $fail) {
         $hour = intval(Illuminate\Support\Str::before($value,':'));
         if ($hour < 9 || $hour > 18) {
           $fail($attribute . ' must be between 09:00 and 18:00');
         }
       }
     ]
1 like
Snapey's avatar
Snapey
Best Answer
Level 122

or you can create a custom rule class

class HourBetween implements Illuminate\Contracts\Validation\Rule
{
  private $start;
  private $end;
  
  public function __construct($start, $end)
  {
    $this->start = $start;
    $this->end = $end;
  }
  
  public function passes($attribute, $value)
  {
    $hour = intval(Illuminate\Support\Str::before($value,':'));
      return $hour >= $this->start && $hour < $this->end;
  }

  public function message()
  {
    return "The :attribute should be between {$this->start}:00 and {$this->end}:00";
  }
}

and then use it like

     'start_time' => [
       'required',
       new HourBetween(9,18),
     ]

https://laravel.com/docs/8.x/validation#custom-validation-rules

1 like

Please or to participate in this conversation.