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

earmsby's avatar

Duration validation rule

I have a field on a form for "Duration" of a musical work. The database stores the duration in # of seconds, but the user inputs the duration like: "01:15:00"

I've written the code to convert "01:15:00" to the integer 4500 so that's all set and it works as long as the user doesn't type something that isn't a valid duration into the field like "01-75-125"

I was looking through the docs for a good way to validate this field along with the other validation I'm already doing. It seemed that there wasn't something out of the box but I could write my own custom validation rule using php artisan make:rule.

Before I undertake that, I wondered if I was overlooking a more obvious and possibly simpler way to do this.

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

You’re correct that Laravel doesn’t have a built-in validation rule specifically for time durations in the format HH:MM:SS. However, you don’t necessarily need to create a custom rule class unless you want to encapsulate more complex logic.

A simple and effective solution is to use the regex validation rule to ensure the input matches the HH:MM:SS format. Here’s how you can do it in your form request or controller:

$request->validate([
    'duration' => [
        'required',
        'regex:/^\d{2}:\d{2}:\d{2}$/'
    ],
]);

This will ensure that the input is exactly two digits, a colon, two digits, a colon, and two digits (e.g., 01:15:00).

Note: This regex will accept values like 99:99:99, so if you want to be stricter (e.g., minutes and seconds should be 0–59), you can use a more advanced regex:

$request->validate([
    'duration' => [
        'required',
        'regex:/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/'
    ],
]);

This version restricts hours to 0023, and minutes/seconds to 0059.

If you need more complex validation (e.g., allowing more than 24 hours), then a custom rule might be warranted. But for most musical durations, the regex above should suffice.

Summary:

  • Use a regex rule for simple validation.
  • Only create a custom rule if you need more complex checks.

Let me know if you need help with the conversion logic or custom rule creation!

1 like
earmsby's avatar

Perfect, that did exactly was I was looking to do!

martinbean's avatar

@earmsby You could have also used Laravel’s built-in date_format rule (since times are a subset of date values):

'duration' => ['required', 'date_format:H:i:s'],

That will validate that the given duration value is in HH:MM:SS format.

1 like

Please or to participate in this conversation.