Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Reference
  4. Constraints
  5. Expression
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Basic Usage
  • Options
    • expression
    • groups
    • message
    • negate
    • payload
    • values

Expression

Edit this page

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 to class or property/method
Class Expression
Validator ExpressionValidator

Basic Usage

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// src/Model/BlogPost.php
namespace App\Model;

use Symfony\Component\Validator\Constraints as Assert;

class BlogPost
{
    private $category;

    private $isTechnicalPost;

    // ...

    public function getCategory()
    {
        return $this->category;
    }

    public function setIsTechnicalPost($isTechnicalPost)
    {
        $this->isTechnicalPost = $isTechnicalPost;
    }

    // ...
}

To validate the object, you have some special requirements:

A) If isTechnicalPost is true, then category must be either php
or symfony;

B) If isTechnicalPost is false, then category can be anything.

One way to accomplish this is with the Expression constraint:

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/Model/BlogPost.php
namespace App\Model;

use Symfony\Component\Validator\Constraints as Assert;

#[Assert\Expression(
    "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()",
    message: 'If this is a tech post, the category should be either php or symfony!',
)]
class BlogPost
{
    // ...
}
1
2
3
4
5
6
# config/validator/validation.yaml
App\Model\BlogPost:
    constraints:
        - Expression:
            expression: "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()"
            message: "If this is a tech post, the category should be either php or symfony!"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    <class name="App\Model\BlogPost">
        <constraint name="Expression">
            <option name="expression">
                this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()
            </option>
            <option name="message">
                If this is a tech post, the category should be either php or symfony!
            </option>
        </constraint>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/Model/BlogPost.php
namespace App\Model;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class BlogPost
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addConstraint(new Assert\Expression([
            'expression' => 'this.getCategory() in ["php", "symfony"] or !this.isTechnicalPost()',
            'message' => 'If this is a tech post, the category should be either php or symfony!',
        ]));
    }

    // ...
}

The expression option is the expression that must return true in order for validation to pass. Learn more about the expression language syntax.

Alternatively, you can set the negate option to false in order to assert that the expression must return true for validation to fail.

6.2

The negate option was introduced in Symfony 6.2.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/Model/BlogPost.php
namespace App\Model;

use Symfony\Component\Validator\Constraints as Assert;

class BlogPost
{
    // ...

    #[Assert\Expression(
        "this.getCategory() in ['php', 'symfony'] or value == false",
        message: 'If this is a tech post, the category should be either php or symfony!',
    )]
    private $isTechnicalPost;

    // ...
}
1
2
3
4
5
6
7
# config/validator/validation.yaml
App\Model\BlogPost:
    properties:
        isTechnicalPost:
            - Expression:
                expression: "this.getCategory() in ['php', 'symfony'] or value == false"
                message: "If this is a tech post, the category should be either php or symfony!"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

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

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class BlogPost
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('isTechnicalPost', new Assert\Expression([
            'expression' => 'this.getCategory() in ["php", "symfony"] or value == false',
            'message' => 'If this is a tech post, the category should be either php or symfony!',
        ]));
    }

    // ...
}

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

Tip

Internally, this expression validator constraint uses a service called validator.expression_language to evaluate the expressions. You can decorate or extend that service to fit your own needs.

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. Learn more about the expression language syntax.

Depending on how you use the constraint, you have access to different 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 default: null

It defines the validation group or groups of this constraint. 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:

Parameter Description
{{ value }} The current (invalid) value
{{ label }} Corresponding form field label

negate

type: boolean default: true

If false, the validation fails when expression returns true.

6.2

The negate option was introduced in Symfony 6.2.

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.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/Model/Analysis.php
namespace App\Model;

use Symfony\Component\Validator\Constraints as Assert;

class Analysis
{
    #[Assert\Expression(
        'value + error_margin < threshold',
        values: ['error_margin' => 0.25, 'threshold' => 1.5],
    )]
    private $metric;

    // ...
}
1
2
3
4
5
6
7
# config/validator/validation.yaml
App\Model\Analysis:
    properties:
        metric:
            - Expression:
                expression: "value + error_margin < threshold"
                values:     { error_margin: 0.25, threshold: 1.5 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!-- config/validator/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

    <class name="App\Model\Analysis">
        <property name="metric">
            <constraint name="Expression">
                <option name="expression">
                    value + error_margin &lt; threshold
                </option>
                <option name="values">
                    <value key="error_margin">0.25</value>
                    <value key="threshold">1.5</value>
                </option>
            </constraint>
        </property>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/Model/Analysis.php
namespace App\Model;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class Analysis
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('metric', new Assert\Expression([
            'expression' => 'value + error_margin < threshold',
            'values' => ['error_margin' => 0.25, 'threshold' => 1.5],
        ]));
    }

    // ...
}
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:

    Symfony 6.2 is backed by

    Symfony 6.2 is backed by

    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Check Code Performance in Dev, Test, Staging & Production

    Check Code Performance in Dev, Test, Staging & Production

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Slava Belokurski, a Symfony contributor

    Thanks Slava Belokurski (@slavchoo) for being a Symfony contributor

    1 commit • 2 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia