New in Symfony 5.1: Validator improvements
May 18, 2020 • 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.
In addition to the new AtLeastOneOf, ExpressionLanguageSyntax and Hostname validators, Symfony 5.1 introduced other validator improvements.
Added alpha3
option to Country
If you set the new alpha3
option to true
in the Country constraint,
the value is checked as a valid ISO 3166-1 alpha-3 three-letter country code
(e.g. ARG
= Argentina) instead of the default ISO 3166-1 alpha-2 two-letter
country code (e.g. AR
= Argentina).
Added alpha3
option to Language
Similar to the previous feature, in the Language constraint we added a new
alpha3
option to allow using ISO 639-2 three-letter language codes
(swe
= Swedish) instead of the default ISO 639-1 two-letter language code
(sv
= Swedish).
Added divisibleBy
option to Count
The new divisibleBy
option added to the Count constraint checks that the
the number of elements of the given collection is divisible by a certain number.
If you need to perform this check in other values that aren't collections, use
the DivisibleBy constraint.
Validation callables
Sometimes you need to reuse Symfony's constraints in places like the
Symfony Console, to validate the answer to a console question. That's why we've
added a new Validation::createCallable()
to create a callable based on the
given constraints:
1 2 3 4 5 6 7 8
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Validation;
$io = new SymfonyStyle($input, $output);
$validation = Validation::createCallable(new NotBlank());
$wsdl = $io->ask('Wsdl location URL', null, $validation);
The argument of createCallable()
is variadic, so you can pass any number
of constraints:
1 2 3 4 5
// ...
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Url;
$validation = Validation::createCallable(new Length(['max' => 255]), new Url());
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.
$constraints = [ new Length(['max' => 255]), new Url() ];
$validation = Validation::createCallable(...$constraints);