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 00–23, and minutes/seconds to 00–59.
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
regexrule 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!