New in Symfony 4.4: Improved Type Constraint
October 14, 2019 • Published by Javier Eguiluz
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 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;
}
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 are closed.
To ensure that comments stay relevant, they are closed for old posts.
Nice! Thx!
Oh good! It's simple but so useful =)