表达式
此约束允许您使用表达式进行更复杂、动态的验证。请参阅基本用法示例。另请参阅Callback,这是一个提供类似灵活性的不同约束。
适用于 | 类或属性/方法 |
类 | 表达式 |
验证器 | ExpressionValidator |
基本用法
假设您有一个类 BlogPost
,其中包含 category
和 isTechnicalPost
属性
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 string $category;
private bool $isTechnicalPost;
// ...
public function getCategory(): string
{
return $this->category;
}
public function setIsTechnicalPost(bool $isTechnicalPost): void
{
$this->isTechnicalPost = $isTechnicalPost;
}
// ...
}
要验证对象,您有一些特殊要求
- A) 如果
isTechnicalPost
为 true,则category
必须是php
- 或
symfony
;
B) 如果 isTechnicalPost
为 false,则 category
可以是任何值。
实现此目的的一种方法是使用 Expression 约束
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
{
// ...
}
expression 选项是必须返回 true 才能通过验证的表达式。了解更多关于表达式语言语法的信息。
或者,您可以将 negate
选项设置为 false
,以断言表达式必须返回 true
才能使验证失败。
有关表达式以及您可以使用的变量的更多信息,请参阅下面的 expression 选项详细信息。
提示
在内部,此表达式验证器约束使用名为 validator.expression_language
的服务来评估表达式。您可以装饰或扩展该服务以满足您自己的需求。
选项
expression
类型: string
[默认选项]
将被评估的表达式。如果表达式评估为 false 值(使用 ==
,而不是 ===
),则验证将失败。了解更多关于表达式语言语法的信息。
根据您使用约束的方式,您可以在表达式中访问不同的变量
this
: 正在验证的对象(例如,BlogPost 的实例);value
: 正在验证的属性的值(仅当约束直接应用于属性时可用);
您还可以在表达式中访问 is_valid()
函数。此函数检查传递给函数的数据是否引发任何验证违规。
message
类型: string
默认值: 此值无效。
当表达式评估为 false 时提供的默认消息。
您可以在此消息中使用以下参数
参数 | 描述 |
---|---|
{{ value }} |
当前(无效)值 |
{{ label }} |
相应的表单字段标签 |
payload
类型: mixed
默认值: null
此选项可用于将任意特定于域的数据附加到约束。Validator 组件不使用配置的有效负载,但其处理完全取决于您。
例如,您可能想要使用多个错误级别,以便根据错误严重性在前端以不同方式呈现失败的约束。
values
类型: array
默认值: []
表达式中使用的自定义变量的值。值可以是任何类型(数字、布尔值、字符串、null 等)
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 float $metric;
// ...
}