Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?