How to Apply only a Subset of all Your Validation Constraints (Validation Groups)

How to Apply only a Subset of all Your Validation Constraints (Validation Groups)

By default, when validating an object all constraints of this class will be checked whether or not they actually pass. In some cases, however, you will need to validate an object against only some constraints on that class. To do this, you can organize each constraint into one or more “validation groups” and then apply validation against one group of constraints.

For example, suppose you have a User class, which is used both when a user registers and when a user updates their contact information later:

  • 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. class User implements UserInterface
    6. {
    7. /**
    8. * @Assert\Email(groups={"registration"})
    9. */
    10. private $email;
    11. /**
    12. * @Assert\NotBlank(groups={"registration"})
    13. * @Assert\Length(min=7, groups={"registration"})
    14. */
    15. private $password;
    16. /**
    17. * @Assert\Length(min=2)
    18. */
    19. private $city;
    20. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\User:
    3. properties:
    4. email:
    5. - Email: { groups: [registration] }
    6. password:
    7. - NotBlank: { groups: [registration] }
    8. - Length: { min: 7, groups: [registration] }
    9. city:
    10. - Length:
    11. min: 2
  • 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="
    6. http://symfony.com/schema/dic/constraint-mapping
    7. https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd
    8. ">
    9. <class name="App\Entity\User">
    10. <property name="email">
    11. <constraint name="Email">
    12. <option name="groups">
    13. <value>registration</value>
    14. </option>
    15. </constraint>
    16. </property>
    17. <property name="password">
    18. <constraint name="NotBlank">
    19. <option name="groups">
    20. <value>registration</value>
    21. </option>
    22. </constraint>
    23. <constraint name="Length">
    24. <option name="min">7</option>
    25. <option name="groups">
    26. <value>registration</value>
    27. </option>
    28. </constraint>
    29. </property>
    30. <property name="city">
    31. <constraint name="Length">
    32. <option name="min">2</option>
    33. </constraint>
    34. </property>
    35. </class>
    36. </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('email', new Assert\Email([
    10. 'groups' => ['registration'],
    11. ]));
    12. $metadata->addPropertyConstraint('password', new Assert\NotBlank([
    13. 'groups' => ['registration'],
    14. ]));
    15. $metadata->addPropertyConstraint('password', new Assert\Length([
    16. 'min' => 7,
    17. 'groups' => ['registration'],
    18. ]));
    19. $metadata->addPropertyConstraint('city', new Assert\Length([
    20. 'min' => 2,
    21. ]));
    22. }
    23. }

With this configuration, there are three validation groups:

Default

Contains the constraints in the current class and all referenced classes that belong to no other group. In this example, it only contains the city field.

User

Equivalent to all constraints of the User object in the Default group. This is always the name of the class. The difference between this and Default is explained in How to Sequentially Apply Validation Groups.

registration

This is a custom validation group, so it only contains the constraints explicitly associated to it. In this example, only the email and password fields.

Constraints in the Default group of a class are the constraints that have either no explicit group configured or that are configured to a group equal to the class name or the string Default.

Caution

When validating just the User object, there is no difference between the Default group and the User group. But, there is a difference if User has embedded objects. For example, imagine User has an address property that contains some Address object and that you’ve added the Valid constraint to this property so that it’s validated when you validate the User object.

If you validate User using the Default group, then any constraints on the Address class that are in the Default group will be used. But, if you validate User using the User validation group, then only constraints on the Address class with the User group will be validated.

In other words, the Default group and the class name group (e.g. User) are identical, except when the class is embedded in another object that’s actually the one being validated.

If you have inheritance (e.g. User extends BaseUser) and you validate with the class name of the subclass (i.e. User), then all constraints in the User and BaseUser will be validated. However, if you validate using the base class (i.e. BaseUser), then only the default constraints in the BaseUser class will be validated.

To tell the validator to use a specific group, pass one or more group names as the third argument to the validate() method:

  1. $errors = $validator->validate($author, null, ['registration']);

If no groups are specified, all constraints that belong to the group Default will be applied.

In a full stack Symfony project, you’ll usually work with validation indirectly through the form library. For information on how to use validation groups inside forms, see How to Define the Validation Groups to Use.

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