当
此约束允许你仅在提供的表达式返回 true 时应用约束验证。 请参阅基本用法以获取示例。
适用于 | 类 或 属性/方法 |
选项 | |
类 | 当 |
验证器 | WhenValidator |
基本用法
假设你有一个类 Discount
,其中包含 type
和 value
属性
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) 如果 type
是 percent
,则 value
必须小于或等于 100;B) 如果 type
是 absolute
,则 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 选项传递自定义变量。
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。