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 5.1: Validator improvements

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

Contributed by
Maxime Perrimond
in #35116.

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

Contributed by
Christian Flothmann
in #35848.

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

Contributed by
Thomas Calvet
in #35783.

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

Contributed by
in #31466.

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:

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:

// ...
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.


awesome news, keep up good work with improving symfony guys!
Or when using an array:

$constraints = [ new Length(['max' => 255]), new Url() ];
$validation = Validation::createCallable(...$constraints);

Comments are closed.

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