跳到内容

GreaterThanOrEqual

编辑此页

验证一个值是否大于或等于另一个值,该值在选项中定义。要强制一个值大于另一个值,请参阅 GreaterThan

基本用法

以下约束确保:

  • Personsiblings 数量大于或等于 5
  • Person 类的 age 大于或等于 18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/Entity/Person.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Person
{
    #[Assert\GreaterThanOrEqual(5)]
    protected int $siblings;

    #[Assert\GreaterThanOrEqual(
        value: 18,
    )]
    protected int $age;
}

比较日期

此约束可用于比较 DateTime 对象与任何日期字符串,该日期字符串 被 DateTime 构造器接受。例如,您可以检查日期是否至少为当天

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

use Symfony\Component\Validator\Constraints as Assert;

class Order
{
    #[Assert\GreaterThanOrEqual('today')]
    protected \DateTimeInterface $deliveryDate;
}

请注意,PHP 将使用服务器配置的时区来解释这些日期。 如果您想固定时区,请将其附加到日期字符串

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

use Symfony\Component\Validator\Constraints as Assert;

class Order
{
    #[Assert\GreaterThanOrEqual('today UTC')]
    protected \DateTimeInterface $deliveryDate;
}

DateTime 类也接受相对日期或时间。 例如,您可以检查上述交货日期是否至少在当前时间之后五个小时开始

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

use Symfony\Component\Validator\Constraints as Assert;

class Order
{
    #[Assert\GreaterThanOrEqual('+5 hours')]
    protected \DateTimeInterface $deliveryDate;
}

选项

groups

类型: array | string 默认值: null

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

message

类型: string 默认值: 该值应大于或等于 {{ compared_value }}。

如果该值不大于或等于比较值,则会显示此消息。

您可以在此消息中使用以下参数:

参数 描述
{{ compared_value }} 下限
{{ compared_value_type }} 期望的值类型
{{ value }} 当前(无效)值

payload

类型: mixed 默认值: null

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

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

propertyPath

类型: string 默认值: null

它定义了用于进行比较的对象属性值。

例如,如果您想将某个对象的 $endDate 属性与同一对象的 $startDate 属性进行比较,请在 $endDate 的比较约束中使用 propertyPath="startDate"

提示

当使用此选项时,它的值在错误消息中以 {{ compared_value_path }} 占位符的形式提供。 尽管不打算将其包含在显示给最终用户的错误消息中,但在使用 API 对客户端进行任何映射逻辑时,它非常有用。

value

类型: mixed [默认选项]

此选项是必需的。 它定义了比较值。 它可以是字符串、数字或对象。

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