LessThanOrEqual
验证一个值是否小于或等于另一个在选项中定义的值。要强制一个值小于另一个值,请参阅 LessThan。
适用于 | 属性或方法 |
类 | LessThanOrEqual |
验证器 | LessThanOrEqualValidator |
基本用法
以下约束确保
Person
的siblings
数量小于或等于5
age
小于或等于80
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\LessThanOrEqual(5)]
protected int $siblings;
#[Assert\LessThanOrEqual(
value: 80,
)]
protected int $age;
}
比较日期
此约束可用于将 DateTime
对象与任何日期字符串进行比较,日期字符串 被 DateTime 构造器接受。例如,您可以像这样检查日期是否必须是今天或过去
1 2 3 4 5 6 7 8 9 10
// src/Entity/Person.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Person
{
#[Assert\LessThanOrEqual('today')]
protected \DateTimeInterface $dateOfBirth;
}
请注意,PHP 将使用服务器配置的时区来解释这些日期。如果您想固定时区,请将其附加到日期字符串
1 2 3 4 5 6 7 8 9 10
// src/Entity/Person.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Person
{
#[Assert\LessThanOrEqual('today UTC')]
protected \DateTimeInterface $dateOfBirth;
}
DateTime
类也接受相对日期或时间。例如,您可以像这样检查一个人是否必须至少 18 岁
1 2 3 4 5 6 7 8 9 10
// src/Entity/Person.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Person
{
#[Assert\LessThanOrEqual('-18 years')]
protected \DateTimeInterface $dateOfBirth;
}
选项
message
type: string
default: This value should be less than or equal to {{ compared_value }}.
如果值不小于或等于比较值,则会显示此消息。
您可以在此消息中使用以下参数
参数 | 描述 |
---|---|
{{ compared_value }} |
上限 |
{{ compared_value_type }} |
期望的值类型 |
{{ value }} |
当前(无效)值 |
payload
type: mixed
default: null
此选项可用于将任意特定于域的数据附加到约束。配置的有效负载不被 Validator 组件使用,但其处理完全取决于您。
例如,您可能想使用 多个错误级别,以便根据错误严重程度在前端以不同方式呈现失败的约束。
propertyPath
type: string
default: null
它定义了对象属性,其值用于进行比较。
例如,如果您想将某个对象的 $endDate
属性与同一对象的 $startDate
属性进行比较,请在 $endDate
的比较约束中使用 propertyPath="startDate"
。
提示
当使用此选项时,它的值在错误消息中作为 {{ compared_value_path }}
占位符可用。虽然不打算将其包含在向最终用户显示的错误消息中,但在使用 API 对客户端进行任何映射逻辑时,它很有用。