Choice

Choice

This constraint is used to ensure that the given value is one of a given set of valid choices. It can also be used to validate that each item in an array of items is one of those valid choices.

Applies toproperty or method
Options
ClassSymfony\Component\Validator\Constraints\Choice
ValidatorSymfony\Component\Validator\Constraints\ChoiceValidator

Basic Usage

The basic idea of this constraint is that you supply it with an array of valid values (this can be done in several ways) and it validates that the value of the given property exists in that array.

If your valid choice list is simple, you can pass them in directly via the choices option:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Author
    5. {
    6. const GENRES = ['fiction', 'non-fiction'];
    7. /**
    8. * @Assert\Choice({"New York", "Berlin", "Tokyo"})
    9. */
    10. protected $city;
    11. /**
    12. * You can also directly provide an array constant to the "choices" option in the annotation
    13. *
    14. * @Assert\Choice(choices=Author::GENRES, message="Choose a valid genre.")
    15. */
    16. protected $genre;
    17. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. city:
    5. - Choice: [New York, Berlin, Tokyo]
    6. genre:
    7. - Choice:
    8. choices: [fiction, non-fiction]
    9. message: Choose a valid genre.
  • 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="city">
    8. <constraint name="Choice">
    9. <value>New York</value>
    10. <value>Berlin</value>
    11. <value>Tokyo</value>
    12. </constraint>
    13. </property>
    14. <property name="genre">
    15. <constraint name="Choice">
    16. <option name="choices">
    17. <value>fiction</value>
    18. <value>non-fiction</value>
    19. </option>
    20. <option name="message">Choose a valid genre.</option>
    21. </constraint>
    22. </property>
    23. </class>
    24. </constraint-mapping>
  • PHP

    1. // src/EntityAuthor.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(
    10. 'city',
    11. new Assert\Choice(['New York', 'Berlin', 'Tokyo'])
    12. );
    13. $metadata->addPropertyConstraint('genre', new Assert\Choice([
    14. 'choices' => ['fiction', 'non-fiction'],
    15. 'message' => 'Choose a valid genre.',
    16. ]));
    17. }
    18. }

Supplying the Choices with a Callback Function

You can also use a callback function to specify your options. This is useful if you want to keep your choices in some central location so that, for example, you can access those choices for validation or for building a select form element:

  1. // src/Entity/Author.php
  2. namespace App\Entity;
  3. class Author
  4. {
  5. public static function getGenres()
  6. {
  7. return ['fiction', 'non-fiction'];
  8. }
  9. }

You can pass the name of this method to the callback option of the Choice constraint.

  • 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\Choice(callback="getGenres")
    8. */
    9. protected $genre;
    10. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. genre:
    5. - Choice: { callback: getGenres }
  • 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="genre">
    8. <constraint name="Choice">
    9. <option name="callback">getGenres</option>
    10. </constraint>
    11. </property>
    12. </class>
    13. </constraint-mapping>
  • PHP

    1. // src/EntityAuthor.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 $genre;
    8. public static function loadValidatorMetadata(ClassMetadata $metadata)
    9. {
    10. $metadata->addPropertyConstraint('genre', new Assert\Choice([
    11. 'callback' => 'getGenres',
    12. ]));
    13. }
    14. }

If the callback is defined in a different class and is static, for example App\Entity\Genre, you can pass the class name and the method as an array.

  • 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\Choice(callback={"App\Entity\Genre", "getGenres"})
    8. */
    9. protected $genre;
    10. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. genre:
    5. - Choice: { callback: [App\Entity\Genre, getGenres] }
  • 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="genre">
    8. <constraint name="Choice">
    9. <option name="callback">
    10. <value>App\Entity\Genre</value>
    11. <value>getGenres</value>
    12. </option>
    13. </constraint>
    14. </property>
    15. </class>
    16. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use App\Entity\Genre;
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. use Symfony\Component\Validator\Mapping\ClassMetadata;
    6. class Author
    7. {
    8. public static function loadValidatorMetadata(ClassMetadata $metadata)
    9. {
    10. $metadata->addPropertyConstraint('genre', new Assert\Choice([
    11. 'callback' => [Genre::class, 'getGenres'],
    12. ]));
    13. }
    14. }

Available Options

callback

type: string|array|Closure

This is a callback method that can be used instead of the choices option to return the choices array. See Supplying the Choices with a Callback Function for details on its usage.

choices

type: array [default option]

A required option (unless callback is specified) - this is the array of options that should be considered in the valid set. The input value will be matched against this array.

groups

type: array | string

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

max

type: integer

If the multiple option is true, then you can use the max option to force no more than XX number of values to be selected. For example, if max is 3, but the input array contains 4 valid items, the validation will fail.

maxMessage

type: string default: You must select at most {{ limit }} choices.

This is the validation error message that’s displayed when the user chooses too many options per the max option.

You can use the following parameters in this message:

ParameterDescription
{{ choices }}A comma-separated list of available choices
{{ value }}The current (invalid) value

New in version 4.3: The {{ choices }} parameter was introduced in Symfony 4.3.

message

type: string default: The value you selected is not a valid choice.

This is the message that you will receive if the multiple option is set to false and the underlying value is not in the valid array of choices.

You can use the following parameters in this message:

ParameterDescription
{{ choices }}A comma-separated list of available choices
{{ value }}The current (invalid) value

min

type: integer

If the multiple option is true, then you can use the min option to force at least XX number of values to be selected. For example, if min is 3, but the input array only contains 2 valid items, the validation will fail.

minMessage

type: string default: You must select at least {{ limit }} choices.

This is the validation error message that’s displayed when the user chooses too few choices per the min option.

You can use the following parameters in this message:

ParameterDescription
{{ choices }}A comma-separated list of available choices
{{ value }}The current (invalid) value

New in version 4.3: The {{ choices }} parameter was introduced in Symfony 4.3.

multiple

type: boolean default: false

If this option is true, the input value is expected to be an array instead of a single, scalar value. The constraint will check that each value of the input array can be found in the array of valid choices. If even one of the input values cannot be found, the validation will fail.

multipleMessage

type: string default: One or more of the given values is invalid.

This is the message that you will receive if the multiple option is set to true and one of the values on the underlying array being checked is not in the array of valid choices.

You can use the following parameters in this message:

ParameterDescription
{{ value }}The current (invalid) value

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.