跳到内容

编辑此页

此约束允许你仅在提供的表达式返回 true 时应用约束验证。 请参阅基本用法以获取示例。

基本用法

假设你有一个类 Discount,其中包含 typevalue 属性

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;
    }
}

要验证该对象,你需要满足一些要求

A) 如果 typepercent,则 value 必须小于或等于 100;B) 如果 typeabsolute,则 value 可以是任何值;C) 无论 type 的值是什么,value 都必须大于 0。

实现此目的的一种方法是使用 When 约束

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 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!')
        ],
    )]
    private ?int $value;

    // ...
}

expression 选项是必须返回 true 才能触发附加约束验证的表达式。 要了解有关表达式语言语法的更多信息,请参阅表达式语法

有关表达式以及你可以使用的变量的更多信息,请参阅下面的 expression 选项详细信息。

选项

expression

类型string

使用表达式语言语法编写的条件,将对其进行评估。如果表达式评估为假值(即使用 ==,而不是 ===),则不会触发约束验证。

要了解有关表达式语言语法的更多信息,请参阅表达式语法

根据你使用约束的方式,你可以在表达式中访问不同的变量

this
正在验证的对象(例如,Discount 的实例)。
value
正在验证的属性的值(仅当约束应用于属性时可用)。
context
ExecutionContextInterface 对象,提供诸如当前验证的类、当前验证的属性名称、违规列表等信息。

7.2

表达式中的 context 变量是在 Symfony 7.2 中引入的。

当你想根据 value 变量的值执行更复杂的验证时,可以使用该变量

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

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

class Discount
{
    #[Assert\When(
        expression: 'value == "percent"',
        constraints: [new Assert\Callback('doComplexValidation')],
    )]
    private ?string $type;
    // ...

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

你还可以使用 values 选项传递自定义变量。

constraints

类型array|Constraint

如果表达式返回 true,则应用一个或多个约束。

groups

类型array | string 默认值null

它定义此约束的验证组。阅读有关验证组的更多信息。

payload

类型mixed 默认值null

此选项可用于将任意特定于域的数据附加到约束。Validator 组件不使用配置的 payload,但其处理完全取决于你。

例如,你可能想要使用多个错误级别,以便根据错误严重性在前端以不同方式呈现失败的约束。

values

类型array 默认值[]

表达式中使用的自定义变量的值。 值可以是任何类型(数字、布尔值、字符串、null 等)

本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本