Expression

Expression

This constraint allows you to use an expression for more complex, dynamic validation. See Basic Usage for an example. See Callback for a different constraint that gives you similar flexibility.

Applies toclass or property/method
Options
ClassSymfony\Component\Validator\Constraints\Expression
ValidatorSymfony\Component\Validator\Constraints\ExpressionValidator

Basic Usage

Imagine you have a class BlogPost with category and isTechnicalPost properties:

  1. // src/Model/BlogPost.php
  2. namespace App\Model;
  3. use Symfony\Component\Validator\Constraints as Assert;
  4. class BlogPost
  5. {
  6. private $category;
  7. private $isTechnicalPost;
  8. // ...
  9. public function getCategory()
  10. {
  11. return $this->category;
  12. }
  13. public function setIsTechnicalPost($isTechnicalPost)
  14. {
  15. $this->isTechnicalPost = $isTechnicalPost;
  16. }
  17. // ...
  18. }

To validate the object, you have some special requirements:

  1. If isTechnicalPost is true, then category must be either php or symfony;
  2. If isTechnicalPost is false, then category can be anything.

One way to accomplish this is with the Expression constraint:

  • Annotations

    1. // src/Model/BlogPost.php
    2. namespace App\Model;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. /**
    5. * @Assert\Expression(
    6. * "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()",
    7. * message="If this is a tech post, the category should be either php or symfony!"
    8. * )
    9. */
    10. class BlogPost
    11. {
    12. // ...
    13. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Model\BlogPost:
    3. constraints:
    4. - Expression:
    5. expression: "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()"
    6. message: "If this is a tech post, the category should be either php or symfony!"
  • 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\Model\BlogPost">
    7. <constraint name="Expression">
    8. <option name="expression">
    9. this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()
    10. </option>
    11. <option name="message">
    12. If this is a tech post, the category should be either php or symfony!
    13. </option>
    14. </constraint>
    15. </class>
    16. </constraint-mapping>
  • PHP

    1. // src/Model/BlogPost.php
    2. namespace App\Model;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class BlogPost
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addConstraint(new Assert\Expression([
    10. 'expression' => 'this.getCategory() in ["php", "symfony"] or !this.isTechnicalPost()',
    11. 'message' => 'If this is a tech post, the category should be either php or symfony!',
    12. ]));
    13. }
    14. // ...
    15. }

The expression option is the expression that must return true in order for validation to pass. To learn more about the expression language syntax, see The Expression Syntax.

Mapping the Error to a Specific Field

You can also attach the constraint to a specific property and still validate based on the values of the entire entity. This is handy if you want to attach the error to a specific field. In this context, value represents the value of isTechnicalPost.

  • Annotations

    1. // src/Model/BlogPost.php
    2. namespace App\Model;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class BlogPost
    5. {
    6. // ...
    7. /**
    8. * @Assert\Expression(
    9. * "this.getCategory() in ['php', 'symfony'] or value == false",
    10. * message="If this is a tech post, the category should be either php or symfony!"
    11. * )
    12. */
    13. private $isTechnicalPost;
    14. // ...
    15. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Model\BlogPost:
    3. properties:
    4. isTechnicalPost:
    5. - Expression:
    6. expression: "this.getCategory() in ['php', 'symfony'] or value == false"
    7. message: "If this is a tech post, the category should be either php or symfony!"
  • 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\Model\BlogPost">
    7. <property name="isTechnicalPost">
    8. <constraint name="Expression">
    9. <option name="expression">
    10. this.getCategory() in ['php', 'symfony'] or value == false
    11. </option>
    12. <option name="message">
    13. If this is a tech post, the category should be either php or symfony!
    14. </option>
    15. </constraint>
    16. </property>
    17. </class>
    18. </constraint-mapping>
  • PHP

    1. // src/Model/BlogPost.php
    2. namespace App\Model;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class BlogPost
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('isTechnicalPost', new Assert\Expression([
    10. 'expression' => 'this.getCategory() in ["php", "symfony"] or value == false',
    11. 'message' => 'If this is a tech post, the category should be either php or symfony!',
    12. ]));
    13. }
    14. // ...
    15. }

For more information about the expression and what variables are available to you, see the expression option details below.

Options

expression

type: string [default option]

The expression that will be evaluated. If the expression evaluates to a false value (using ==, not ===), validation will fail.

To learn more about the expression language syntax, see The Expression Syntax.

Inside of the expression, you have access to up to 2 variables:

Depending on how you use the constraint, you have access to 1 or 2 variables in your expression:

  • this: The object being validated (e.g. an instance of BlogPost);
  • value: The value of the property being validated (only available when the constraint is applied directly to a property);

groups

type: array | string

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

message

type: string default: This value is not valid.

The default message supplied when the expression evaluates to false.

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.

values

type: array default: []

The values of the custom variables used in the expression. Values can be of any type (numeric, boolean, strings, null, etc.)

  • Annotations

    1. // src/Model/Analysis.php
    2. namespace App\Model;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Analysis
    5. {
    6. /**
    7. * @Assert\Expression(
    8. * "value + error_margin < threshold",
    9. * values = { "error_margin": 0.25, "threshold": 1.5 }
    10. * )
    11. */
    12. private $metric;
    13. // ...
    14. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Model\Analysis:
    3. properties:
    4. metric:
    5. - Expression:
    6. expression: "value + error_margin < threshold"
    7. values: { error_margin: 0.25, threshold: 1.5 }
  • 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\Model\Analysis">
    7. <property name="metric">
    8. <constraint name="Expression">
    9. <option name="expression">
    10. value + error_margin &lt; threshold
    11. </option>
    12. <option name="values">
    13. <value key="error_margin">0.25</value>
    14. <value key="threshold">1.5</value>
    15. </option>
    16. </constraint>
    17. </property>
    18. </class>
    19. </constraint-mapping>
  • PHP

    1. // src/Model/Analysis.php
    2. namespace App\Model;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Analysis
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('metric', new Assert\Expression([
    10. 'expression' => 'value + error_margin < threshold',
    11. 'values' => ['error_margin' => 0.25, 'threshold' => 1.5],
    12. ]));
    13. }
    14. // ...
    15. }

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