唯一性
验证给定集合中的所有元素是否唯一(没有元素出现多次)。默认情况下,元素会进行严格比较,因此 '7' 和 7 被认为是不同的元素(分别是字符串和整数)。如果你想应用任何其他比较逻辑,请使用 normalizer 选项。
另请参阅
如果你想对集合中的元素应用不同的验证约束,或者想确保某些集合键存在,请使用 Collection 约束。
另请参阅
如果你想验证实体属性的值在同一类型的所有实体中是否唯一(例如,所有用户的注册邮箱),请使用 UniqueEntity 约束。
| 应用于 | 属性或方法 |
| 类 | 唯一性 |
| 验证器 | UniqueValidator |
基本用法
此约束可以应用于任何 array 或 \Traversable 类型的属性。在以下示例中,$contactEmails 是一个字符串数组
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\Unique]
protected array $contactEmails;
}
选项
字段
类型: array | string
这定义了集合中应该检查唯一性的键。默认情况下,所有集合键都会检查唯一性。
例如,假设你有一个包含 latitude、longitude 和 label 字段的项集合。默认情况下,只要标签不同,你就可以有重复的坐标。通过设置 fields 选项,你可以强制纬度+经度在集合中是唯一的
1 2 3 4 5 6 7 8 9 10
// src/Entity/PointOfInterest.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class PointOfInterest
{
#[Assert\Unique(fields: ['latitude', 'longitude'])]
protected array $coordinates;
}
错误路径
类型: string 默认值: null
7.2
errorPath 选项在 Symfony 7.2 中引入。
如果发生验证错误,默认情况下,错误消息会绑定到集合中的第一个元素。使用此选项可以将错误消息绑定到集合中第一个项内的特定字段。
此选项的值必须使用任何 有效的 PropertyAccess 语法(例如,'point_of_interest','user.email')。
消息
类型: string 默认值: This collection should contain only unique elements.
如果集合中至少有一个元素重复,将显示此消息。
你可以在此消息中使用以下参数
| 参数 | 描述 |
|---|---|
{{ value }} |
当前的(无效的)值 |