LessThan
验证一个值是否小于另一个在选项中定义的值。要强制一个值小于或等于另一个值,请参阅 LessThanOrEqual。要强制一个值大于另一个值,请参阅 GreaterThan。
应用于 | 属性或方法 |
类 | LessThan |
验证器 | LessThanValidator |
基本用法
以下约束确保
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\LessThan(5)]
protected int $siblings;
#[Assert\LessThan(
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\LessThan('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\LessThan('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\LessThan('-18 years')]
protected \DateTimeInterface $dateOfBirth;
}
选项
message
类型: string
默认值: 此值应小于 {{ compared_value }}.
如果该值不小于比较值,将显示此消息。
您可以在此消息中使用以下参数
参数 | 描述 |
---|---|
{{ compared_value }} |
上限 |
{{ compared_value_type }} |
期望的值类型 |
{{ value }} |
当前 (无效) 值 |
payload
类型: mixed
默认值: null
此选项可用于将任意特定于域的数据附加到约束。配置的 payload 不被 Validator 组件使用,但其处理完全取决于您。
例如,您可能想使用几个错误级别,以便根据错误严重性在前端以不同方式呈现失败的约束。
propertyPath
类型: string
默认值: null
它定义了对象属性,其值用于进行比较。
例如,如果您想将某个对象的 $endDate
属性与同一对象的 $startDate
属性进行比较,请在 $endDate
的比较约束中使用 propertyPath="startDate"
。
提示
当使用此选项时,它的值在错误消息中作为 {{ compared_value_path }}
占位符可用。虽然不打算将其包含在向最终用户显示的错误消息中,但在使用 API 对客户端进行任何映射逻辑时,它很有用。
这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。