How to Sequentially Apply Validation Groups

How to Sequentially Apply Validation Groups

In some cases, you want to validate your groups by steps. To do this, you can use the GroupSequence feature. In this case, an object defines a group sequence, which determines the order groups should be validated.

For example, suppose you have a User class and want to validate that the username and the password are different only if all other validation passes (in order to avoid multiple error messages).

  • Annotations

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. use Symfony\Component\Security\Core\User\UserInterface;
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. /**
    6. * @Assert\GroupSequence({"User", "Strict"})
    7. */
    8. class User implements UserInterface
    9. {
    10. /**
    11. * @Assert\NotBlank
    12. */
    13. private $username;
    14. /**
    15. * @Assert\NotBlank
    16. */
    17. private $password;
    18. /**
    19. * @Assert\IsTrue(message="The password cannot match your username", groups={"Strict"})
    20. */
    21. public function isPasswordSafe()
    22. {
    23. return ($this->username !== $this->password);
    24. }
    25. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\User:
    3. group_sequence:
    4. - User
    5. - Strict
    6. getters:
    7. passwordSafe:
    8. - 'IsTrue':
    9. message: 'The password cannot match your username'
    10. groups: [Strict]
    11. properties:
    12. username:
    13. - NotBlank: ~
    14. password:
    15. - NotBlank: ~
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\User">
    7. <property name="username">
    8. <constraint name="NotBlank"/>
    9. </property>
    10. <property name="password">
    11. <constraint name="NotBlank"/>
    12. </property>
    13. <getter property="passwordSafe">
    14. <constraint name="IsTrue">
    15. <option name="message">The password cannot match your username</option>
    16. <option name="groups">
    17. <value>Strict</value>
    18. </option>
    19. </constraint>
    20. </getter>
    21. <group-sequence>
    22. <value>User</value>
    23. <value>Strict</value>
    24. </group-sequence>
    25. </class>
    26. </constraint-mapping>
  • PHP

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class User
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('username', new Assert\NotBlank());
    10. $metadata->addPropertyConstraint('password', new Assert\NotBlank());
    11. $metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue([
    12. 'message' => 'The password cannot match your first name',
    13. 'groups' => ['Strict'],
    14. ]));
    15. $metadata->setGroupSequence(['User', 'Strict']);
    16. }
    17. }

In this example, it will first validate all constraints in the group User (which is the same as the Default group). Only if all constraints in that group are valid, the second group, Strict, will be validated.

Caution

As you have already seen in How to Apply only a Subset of all Your Validation Constraints (Validation Groups), the Default group and the group containing the class name (e.g. User) were identical. However, when using Group Sequences, they are no longer identical. The Default group will now reference the group sequence, instead of all constraints that do not belong to any group.

This means that you have to use the {ClassName} (e.g. User) group when specifying a group sequence. When using Default, you get an infinite recursion (as the Default group references the group sequence, which will contain the Default group which references the same group sequence, …).

Caution

Calling validate() with a group in the sequence (Strict in previous example) will cause a validation only with that group and not with all the groups in the sequence. This is because sequence is now referred to Default group validation.

You can also define a group sequence in the validation_groups form option:

  1. // src/Form/MyType.php
  2. namespace App\Form;
  3. use Symfony\Component\Form\AbstractType;
  4. use Symfony\Component\OptionsResolver\OptionsResolver;
  5. use Symfony\Component\Validator\Constraints\GroupSequence;
  6. // ...
  7. class MyType extends AbstractType
  8. {
  9. // ...
  10. public function configureOptions(OptionsResolver $resolver)
  11. {
  12. $resolver->setDefaults([
  13. 'validation_groups' => new GroupSequence(['First', 'Second']),
  14. ]);
  15. }
  16. }

Group Sequence Providers

Imagine a User entity which can be a normal user or a premium user. When it’s a premium user, some extra constraints should be added to the user entity (e.g. the credit card details). To dynamically determine which groups should be activated, you can create a Group Sequence Provider. First, create the entity and a new constraint group called Premium:

  • Annotations

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class User
    5. {
    6. /**
    7. * @Assert\NotBlank
    8. */
    9. private $name;
    10. /**
    11. * @Assert\CardScheme(
    12. * schemes={"VISA"},
    13. * groups={"Premium"},
    14. * )
    15. */
    16. private $creditCard;
    17. // ...
    18. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\User:
    3. properties:
    4. name:
    5. - NotBlank: ~
    6. creditCard:
    7. - CardScheme:
    8. schemes: [VISA]
    9. groups: [Premium]
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\User">
    7. <property name="name">
    8. <constraint name="NotBlank"/>
    9. </property>
    10. <property name="creditCard">
    11. <constraint name="CardScheme">
    12. <option name="schemes">
    13. <value>VISA</value>
    14. </option>
    15. <option name="groups">
    16. <value>Premium</value>
    17. </option>
    18. </constraint>
    19. </property>
    20. <!-- ... -->
    21. </class>
    22. </constraint-mapping>
  • PHP

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class User
    6. {
    7. private $name;
    8. private $creditCard;
    9. // ...
    10. public static function loadValidatorMetadata(ClassMetadata $metadata)
    11. {
    12. $metadata->addPropertyConstraint('name', new Assert\NotBlank());
    13. $metadata->addPropertyConstraint('creditCard', new Assert\CardScheme([
    14. 'schemes' => ['VISA'],
    15. 'groups' => ['Premium'],
    16. ]));
    17. }
    18. }

Now, change the User class to implement Symfony\Component\Validator\GroupSequenceProviderInterface and add the [getGroupSequence()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Validator/GroupSequenceProviderInterface.php "Symfony\Component\Validator\GroupSequenceProviderInterface::getGroupSequence()"), method, which should return an array of groups to use:

  1. // src/Entity/User.php
  2. namespace App\Entity;
  3. // ...
  4. use Symfony\Component\Validator\GroupSequenceProviderInterface;
  5. class User implements GroupSequenceProviderInterface
  6. {
  7. // ...
  8. public function getGroupSequence()
  9. {
  10. // when returning a simple array, if there's a violation in any group
  11. // the rest of groups are not validated. E.g. if 'User' fails,
  12. // 'Premium' and 'Api' are not validated:
  13. return ['User', 'Premium', 'Api'];
  14. // when returning a nested array, all the groups included in each array
  15. // are validated. E.g. if 'User' fails, 'Premium' is also validated
  16. // (and you'll get its violations too) but 'Api' won't be validated:
  17. return [['User', 'Premium'], 'Api'];
  18. }
  19. }

At last, you have to notify the Validator component that your User class provides a sequence of groups to be validated:

  • Annotations

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. // ...
    4. /**
    5. * @Assert\GroupSequenceProvider
    6. */
    7. class User implements GroupSequenceProviderInterface
    8. {
    9. // ...
    10. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\User:
    3. group_sequence_provider: true
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
    6. https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    7. <class name="App\Entity\User">
    8. <group-sequence-provider/>
    9. <!-- ... -->
    10. </class>
    11. </constraint-mapping>
  • PHP

    1. // src/Entity/User.php
    2. namespace App\Entity;
    3. // ...
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class User implements GroupSequenceProviderInterface
    6. {
    7. // ...
    8. public static function loadValidatorMetadata(ClassMetadata $metadata)
    9. {
    10. $metadata->setGroupSequenceProvider(true);
    11. // ...
    12. }
    13. }

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.