Collection

Collection

This constraint is used when the underlying data is a collection (i.e. an array or an object that implements Traversable and ArrayAccess), but you’d like to validate different keys of that collection in different ways. For example, you might validate the email key using the Email constraint and the inventory key of the collection with the Range constraint.

This constraint can also make sure that certain collection keys are present and that extra keys are not present.

See also

If you want to validate that all the elements of the collection are unique use the Unique constraint.

Applies toproperty or method
Options
ClassSymfony\Component\Validator\Constraints\Collection
ValidatorSymfony\Component\Validator\Constraints\CollectionValidator

Basic Usage

The Collection constraint allows you to validate the different keys of a collection individually. Take the following example:

  1. // src/Entity/Author.php
  2. namespace App\Entity;
  3. class Author
  4. {
  5. protected $profileData = [
  6. 'personal_email' => '...',
  7. 'short_bio' => '...',
  8. ];
  9. public function setProfileData($key, $value)
  10. {
  11. $this->profileData[$key] = $value;
  12. }
  13. }

To validate that the personal_email element of the profileData array property is a valid email address and that the short_bio element is not blank but is no longer than 100 characters in length, you would do the following:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Author
    5. {
    6. /**
    7. * @Assert\Collection(
    8. * fields = {
    9. * "personal_email" = @Assert\Email,
    10. * "short_bio" = {
    11. * @Assert\NotBlank,
    12. * @Assert\Length(
    13. * max = 100,
    14. * maxMessage = "Your short bio is too long!"
    15. * )
    16. * }
    17. * },
    18. * allowMissingFields = true
    19. * )
    20. */
    21. protected $profileData = [
    22. 'personal_email' => '...',
    23. 'short_bio' => '...',
    24. ];
    25. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. profileData:
    5. - Collection:
    6. fields:
    7. personal_email:
    8. - Email: ~
    9. short_bio:
    10. - NotBlank: ~
    11. - Length:
    12. max: 100
    13. maxMessage: Your short bio is too long!
    14. allowMissingFields: 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 https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\Author">
    7. <property name="profileData">
    8. <constraint name="Collection">
    9. <option name="fields">
    10. <value key="personal_email">
    11. <constraint name="Email"/>
    12. </value>
    13. <value key="short_bio">
    14. <constraint name="NotBlank"/>
    15. <constraint name="Length">
    16. <option name="max">100</option>
    17. <option name="maxMessage">Your short bio is too long!</option>
    18. </constraint>
    19. </value>
    20. </option>
    21. <option name="allowMissingFields">true</option>
    22. </constraint>
    23. </property>
    24. </class>
    25. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Author
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('profileData', new Assert\Collection([
    10. 'fields' => [
    11. 'personal_email' => new Assert\Email(),
    12. 'short_bio' => [
    13. new Assert\NotBlank(),
    14. new Assert\Length([
    15. 'max' => 100,
    16. 'maxMessage' => 'Your short bio is too long!',
    17. ]),
    18. ],
    19. ],
    20. 'allowMissingFields' => true,
    21. ]));
    22. }
    23. }

Presence and Absence of Fields

By default, this constraint validates more than whether or not the individual fields in the collection pass their assigned constraints. In fact, if any keys of a collection are missing or if there are any unrecognized keys in the collection, validation errors will be thrown.

If you would like to allow for keys to be absent from the collection or if you would like “extra” keys to be allowed in the collection, you can modify the allowMissingFields and allowExtraFields options respectively. In the above example, the allowMissingFields option was set to true, meaning that if either of the personal_email or short_bio elements were missing from the $personalData property, no validation error would occur.

Required and Optional Field Constraints

Constraints for fields within a collection can be wrapped in the Required or Optional constraint to control whether they should always be applied (Required) or only applied when the field is present (Optional).

For instance, if you want to require that the personal_email field of the profileData array is not blank and is a valid email but the alternate_email field is optional but must be a valid email if supplied, you can do the following:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Author
    5. {
    6. /**
    7. * @Assert\Collection(
    8. * fields={
    9. * "personal_email" = @Assert\Required({@Assert\NotBlank, @Assert\Email}),
    10. * "alternate_email" = @Assert\Optional(@Assert\Email)
    11. * }
    12. * )
    13. */
    14. protected $profileData = ['personal_email' => '[email protected]'];
    15. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. profile_data:
    5. - Collection:
    6. fields:
    7. personal_email:
    8. - Required:
    9. - NotBlank: ~
    10. - Email: ~
    11. alternate_email:
    12. - Optional:
    13. - Email: ~
  • 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\Author">
    7. <property name="profile_data">
    8. <constraint name="Collection">
    9. <option name="fields">
    10. <value key="personal_email">
    11. <constraint name="Required">
    12. <constraint name="NotBlank"/>
    13. <constraint name="Email"/>
    14. </constraint>
    15. </value>
    16. <value key="alternate_email">
    17. <constraint name="Optional">
    18. <constraint name="Email"/>
    19. </constraint>
    20. </value>
    21. </option>
    22. </constraint>
    23. </property>
    24. </class>
    25. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Author
    6. {
    7. protected $profileData = ['personal_email'];
    8. public static function loadValidatorMetadata(ClassMetadata $metadata)
    9. {
    10. $metadata->addPropertyConstraint('profileData', new Assert\Collection([
    11. 'fields' => [
    12. 'personal_email' => new Assert\Required([
    13. new Assert\NotBlank(),
    14. new Assert\Email(),
    15. ]),
    16. 'alternate_email' => new Assert\Optional(new Assert\Email()),
    17. ],
    18. ]));
    19. }
    20. }

Even without allowMissingFields set to true, you can now omit the alternate_email property completely from the profileData array, since it is Optional. However, if the personal_email field does not exist in the array, the NotBlank constraint will still be applied (since it is wrapped in Required) and you will receive a constraint violation.

When you define groups in nested constraints they are automatically added to the Collection constraint itself so it can be traversed for all nested groups. Take the following example:

  1. use Symfony\Component\Validator\Constraints as Assert;
  2. $constraint = new Assert\Collection([
  3. 'fields' => [
  4. 'name' => new Assert\NotBlank(['groups' => 'basic']),
  5. 'email' => new Assert\NotBlank(['groups' => 'contact']),
  6. ],
  7. ]);

This will result in the following configuration:

  1. $constraint = new Assert\Collection([
  2. 'fields' => [
  3. 'name' => new Assert\Required([
  4. 'constraints' => new Assert\NotBlank(['groups' => 'basic']),
  5. 'groups' => ['basic', 'strict'],
  6. ]),
  7. 'email' => new Assert\Required([
  8. "constraints" => new Assert\NotBlank(['groups' => 'contact']),
  9. 'groups' => ['basic', 'strict'],
  10. ]),
  11. ],
  12. 'groups' => ['basic', 'strict'],
  13. ]);

The default allowMissingFields option requires the fields in all groups. So when validating in contact group, $name can be empty but the key is still required. If this is not the intended behavior, use the Optional constraint explicitly instead of Required.

Options

allowExtraFields

type: boolean default: false

If this option is set to false and the underlying collection contains one or more elements that are not included in the fields option, a validation error will be returned. If set to true, extra fields are OK.

allowMissingFields

type: boolean default: false

If this option is set to false and one or more fields from the fields option are not present in the underlying collection, a validation error will be returned. If set to true, it’s OK if some fields in the fields option are not present in the underlying collection.

extraFieldsMessage

type: string default: This field was not expected.

The message shown if allowExtraFields is false and an extra field is detected.

You can use the following parameters in this message:

ParameterDescription
{{ field }}The key of the extra field detected

fields

type: array [default option]

This option is required and is an associative array defining all of the keys in the collection and, for each key, exactly which validator(s) should be executed against that element of the collection.

groups

type: array | string

It defines the validation group or groups this constraint belongs to. Read more about validation groups.

missingFieldsMessage

type: string default: This field is missing.

The message shown if allowMissingFields is false and one or more fields are missing from the underlying collection.

You can use the following parameters in this message:

ParameterDescription
{{ field }}The key of the missing field defined in fields

payload

type: mixed default: null

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to you.

For example, you may want to use several error levels to present failed constraints differently in the front-end depending on the severity of the error.

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