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 in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version

New in Symfony 4.4: Improved Type Constraint

Contributed by
Jan Schädlich
in #31351.

The Type constraint included in the Validator component validates that a given value is of a specific data type. This type can be any of the valid PHP types, any of the PHP ctype functions (e.g. alnum, alpha, digit, etc.) and also the FQCN of any class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\Type("Ramsey\Uuid\UuidInterface")
     */
    protected $id;

    /**
     * @Assert\Type("string")
     */
    protected $firstName;

    // ...
}

Starting from Symfony 4.4, the checked type can be an array of types, so you can validate that the given value type is one of several possible types. In the following example, the $accessCode property can contain only letters or only digits, but not both:

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

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    // ...

    /**
     * @Assert\Type(type={"alpha", "digit"})
     */
    protected $accessCode;
}

Comments

Nice! Thx!
Oh good! It's simple but so useful =)

Comments are closed.

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