March 13, 2020 Javier Eguiluz

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: