跳到内容

AtLeastOneOf

编辑此页

此约束检查值是否满足至少一个给定的约束。一旦满足一个约束,验证就会停止。

基本用法

以下约束确保

  • Student 的 password 要么包含 #,要么至少 10 个字符长;
  • Student 的 grades 是一个数组,其中包含至少 3 个元素,或者每个元素都大于或等于 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/Entity/Student.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Student
{
    #[Assert\AtLeastOneOf([
        new Assert\Regex('/#/'),
        new Assert\Length(min: 10),
    ])]
    protected string $plainPassword;

    #[Assert\AtLeastOneOf([
        new Assert\Count(min: 3),
        new Assert\All(
            new Assert\GreaterThanOrEqual(5)
        ),
    ])]
    protected array $grades;
}

选项

constraints

类型: array [默认选项]

此必需选项是验证约束的数组,为了验证成功,必须满足其中至少一个约束。

includeInternalMessages

类型: boolean 默认值: true

如果设置为 true,则在验证失败时显示的消息将包含内部约束的消息列表。有关示例,请参见 message 选项。

message

类型: string 默认值: This value should satisfy at least one of the following constraints:

这是验证失败时将显示的消息的介绍。默认情况下,它将跟随内部约束的消息列表(可通过 includeInternalMessages 选项配置)。例如,如果上面的 grades 属性验证失败,则消息将是:This value should satisfy at least one of the following constraints: [1] This collection should contain 3 elements or more. [2] Each element of this collection should satisfy its own set of constraints.

messageCollection

类型: string 默认值: Each element of this collection should satisfy its own set of constraints.

这是验证失败时将显示的消息,且内部约束为 AllCollection。有关示例,请参见 message 选项。

groups

类型: array | string 默认值: null

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

payload

类型: mixed 默认值: null

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

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

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