跳到内容

复合

编辑此页

与其他约束相反,此约束不能单独使用。相反,它允许您通过扩展约束来创建自己的可重用约束集,表示在整个应用程序中一致使用的规则。

适用于 属性或方法
复合
验证器 复合验证器

基本用法

假设您在不同的地方需要验证用户密码,您可以创建自己的命名集或需求,以便在任何地方一致地重用

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

use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;

#[\Attribute]
class PasswordRequirements extends Compound
{
    protected function getConstraints(array $options): array
    {
        return [
            new Assert\NotBlank(),
            new Assert\Type('string'),
            new Assert\Length(['min' => 12]),
            new Assert\NotCompromisedPassword(),
            new Assert\PasswordStrength(['minScore' => 4]),
        ];
    }
}

如果您想在其他类中将其用作属性,请将 #[\Attribute] 添加到约束类。如果约束具有配置选项,请将它们定义为约束类上的公共属性。

您现在可以在任何需要的地方使用它

1
2
3
4
5
6
7
8
9
10
// src/Entity/User.php
namespace App\Entity\User;

use App\Validator\Constraints as Assert;

class User
{
    #[Assert\PasswordRequirements]
    public string $plainPassword;
}

验证组和负载可以通过构造函数传递

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

use App\Validator\Constraints as Assert;

class User
{
    #[Assert\PasswordRequirements(
        groups: ['registration'],
        payload: ['severity' => 'error'],
    )]
    public string $plainPassword;
}

7.2

Symfony 7.2 中引入了支持将验证组和负载传递给 Compound 类的构造函数。

选项

groups

类型: array | string 默认值: null

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

payload

类型: mixed 默认值: null

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

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

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