Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

New in Symfony 4.3: Timezone validator

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

The list of Symfony constraints covers most of the common validation needs for web sites and applications. However, we keep listening to your feedback and adding new constraints proposed by the community.

In Symfony 4.3, we've added a new Timezone constraint to check that the given value is one of the valid timezones defined by PHP (e.g. Africa/Nairobi).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// src/Entity/UserSettings.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class UserSettings
{
    /**
     * @Assert\Timezone
     */
    protected $timezone;
}

In addition to the common options defined by most constraints (groups, message, payload) this constraint defines two additional options: zone (to restrict valid timezones to a geographical zone such as Asia or Australia) and countryCode (to restrict valid timezones to a single country):

1
2
3
4
5
6
7
8
9
// Consider valid only the timezones from countries in America continent

/** @Assert\Timezone(zone=\DateTimeZone::AMERICA) */
protected $timezone;

// Consider valid only the Chinese timezones

/** @Assert\Timezone(zone=\DateTimeZone::PER_COUNTRY, countryCode="CN") */
protected $timezone;
Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

We're definitely going to use this when we will migrate to Symfony 4 :D
Thanks! Obviously version 4.3 is the best! Just add the option to doctrine a shorcut to obtain a collection in a query, without having to convert it yourself.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.