Validating specific timezones in Laravel
Laravel provides a timezone validation rule out of the box which you can use to validate if a given value is a valid timezone or not.
$request->validate([
'timezone' => 'timezone',
]);
But what if you want to validate if a given value is a valid timezone but only from a specific set of timezones? For instance, you want to validate if a given value is a valid timezone but only from the set of timezones that are available in the US.
This PR for Laravel 10.x just addressed this issue. Now, you can pass a region
parameter to the timezone
validation rule to validate if a given value is a valid timezone but only from a specific region.
So, for instance, if you want to validate if a given value is a valid timezone but only from the set of timezones that are available in the US, you can do it like so.
$request->validate([
'timezone' => 'timezone:Per_country,US',
]);
Or if you want the timezones from the Africa region, you can do it like so.
$request->validate([
'timezone' => 'timezone:Africa',
]);
The feature utilizes PHP’s DateTimeZone::listIdentifiers() method under the hood to fetch the list of timezones from a given region.
You can read about it to learn which timezone regions are available for validation.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.