Skip to content

When

Edit this page

This constraint allows you to apply constraints validation only if the provided expression returns true. See Basic Usage for an example.

Applies to class or property/method
Options
Class When
Validator WhenValidator

Basic Usage

Imagine you have a class Discount with type and value properties:

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

class Discount
{
    private ?string $type;

    private ?int $value;

    // ...

    public function getType(): ?string
    {
        return $this->type;
    }

    public function getValue(): ?int
    {
        return $this->value;
    }
}

To validate the object, you have some requirements:

A) If type is percent, then value must be less than or equal 100; B) If type is not percent, then value must be less than 9999; C) No matter the value of type, the value must be greater than 0.

One way to accomplish this is with the When constraint:

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

use Symfony\Component\Validator\Constraints as Assert;

class Discount
{
    #[Assert\GreaterThan(0)]
    #[Assert\When(
        expression: 'this.getType() == "percent"',
        constraints: [
            new Assert\LessThanOrEqual(100, message: 'The value should be between 1 and 100!')
        ],
        otherwise: [
            new Assert\LessThan(9999, message: 'The value should be less than 9999!')
        ],
    )]
    private ?int $value;

    // ...
}

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

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

Options

expression

type: string|Closure

The condition evaluated to decide if the constraint is applied or not. It can be defined as a closure or a string using the expression language syntax. If the result is a falsey value (false, null, 0, an empty string or an empty array) the constraints defined in the constraints option won't be applied but the constraints defined in otherwise option (if provided) will be applied.

When using an expression, you access to the following variables:

this
The object being validated (e.g. an instance of Discount).
value
The value of the property being validated (only available when the constraint is applied to a property).
context
The ExecutionContextInterface object that provides information such as the currently validated class, the name of the currently validated property, the list of violations, etc.

7.2

The context variable in expressions was introduced in Symfony 7.2.

When using a closure, the first argument is the object being validated.

7.3

The support for closures in the expression option was introduced in Symfony 7.3 and requires PHP 8.5.

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
26
27
28
29
30
// src/Model/Discount.php
namespace App\Model;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class Discount
{
    // either using an expression...
    #[Assert\When(
        expression: 'value == "percent"',
        constraints: [new Assert\Callback('doComplexValidation')],
    )]

    // ... or using a closure
    #[Assert\When(
        expression: static function (Discount $discount) {
            return $discount->getType() === 'percent';
        },
        constraints: [new Assert\Callback('doComplexValidation')],
    )]
    private ?string $type;

    // ...

    public function doComplexValidation(ExecutionContextInterface $context, $payload): void
    {
        // ...
    }
}

You can also pass custom variables using the values option.

constraints

type: array|Constraint

One or multiple constraints that are applied if the expression returns true.

otherwise

type: array|Constraint

One or multiple constraints that are applied if the expression returns false.

7.3

The otherwise option was introduced in Symfony 7.3.

groups

type: array | string default: null

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

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

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