Symfony News

New in Symfony 5.1: Reusable sets of constraints

Maxime Steinhausser

Contributed by
Maxime Steinhausser
in #34334.

In certain applications is common to reuse the same set of constraints in multiple places. Consider for example an application that allows to register users, change passwords, remember forgotten passwords, etc. That application may use different DTOs for each feature but all of them contain the new user password, which must be validated in the same way in all cases.

In Symfony 5.1, you can quickly create a validator reusing other constraints, no matter if they are built-in or custom made, thanks to the new Compound constraint:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespace App\Validator;

use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotCompromisedPassword;
use Symfony\Component\Validator\Constraints\Type;

/**
 * @Annotation
 */
class MatchesPasswordRequirements extends Compound
{
    protected function getConstraints(array $options): array
    {
        return [
            new NotBlank(),
            new Type('string'),
            new Length(['min' => 12]),
            new NotCompromisedPassword(),
        ];
    }
}

Now you can apply this constraint to your objects as usual:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
namespace App\Dto;

// ...
use App\Validator\MatchesPasswordRequirements;

class ChangePasswordDto
{
    /**
     * @MatchesPasswordRequirements
     */
    private $newPassword;

    // ...
}

Validate constraints sequentiallyΒΆ

Contributed by
Maxime Steinhausser
in #34456.

In Symfony 5.1 we also added a different, but related, feature to validate a set of constraints sequentially. This was already possible thanks to the GroupSequence constraint, but in Symfony 5.1 we simplified this feature with the introduction of a new Sequentially constraint.

The argument of the Sequentially constraint is a set of one or more constraints. Symfony will apply them in that same order and if any of them fails, it will stop and the rest of constraints won't be tested. This is useful to prevent both unexpected type exceptions thrown by some constraints and unnecessary calls to slow constraints:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/**
 * @var string
 *
 * @Assert\Sequentially({
 *     @Assert\Type("string"),
 *     @Assert\Length(min="4"),
 *     @Assert\Regex("[a-z]"),
 *     @SomeCustomConstraintWithHeavyExternalCalls(),
 * })
 */
public $someProperty;

Be trained by Symfony experts - 2020-03-16 Lille - 2020-03-16 Lyon - 2020-03-16 Lyon


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook