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 thevalid 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.phpnamespaceApp\Entity;useSymfony\Component\Validator\ConstraintsasAssert;classAuthor{/** * @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.phpnamespaceApp\Entity;useSymfony\Component\Validator\ConstraintsasAssert;classAuthor{// .../** * @Assert\Type(type={"alpha", "digit"}) */protected$accessCode;} |