Choice
此约束用于确保给定值是一组给定的有效选项之一。它也可以用于验证项目数组中的每个项目是否是这些有效选项之一。
适用于 | 属性或方法 |
类 | Choice |
验证器 | ChoiceValidator |
基本用法
此约束的基本思想是,您为其提供一组有效值(可以通过多种方式完成),并且它验证给定属性的值是否存在于该数组中。
如果您的有效选项列表很简单,则可以直接通过 choices 选项传入它们
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// src/Entity/Author.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
public const GENRES = ['fiction', 'non-fiction'];
#[Assert\Choice(['New York', 'Berlin', 'Tokyo'])]
protected string $city;
#[Assert\Choice(choices: Author::GENRES, message: 'Choose a valid genre.')]
protected string $genre;
}
使用回调函数提供选项
您还可以使用回调函数来指定您的选项。如果您想将选项保存在某个中心位置,以便例如,您可以访问这些选项以进行验证或构建选择表单元素,这将非常有用
1 2 3 4 5 6 7 8 9 10
// src/Entity/Author.php
namespace App\Entity;
class Author
{
public static function getGenres(): array
{
return ['fiction', 'non-fiction'];
}
}
您可以将此方法的名称传递给 Choice
约束的 callback 选项。
1 2 3 4 5 6 7 8 9 10
// src/Entity/Author.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
#[Assert\Choice(callback: 'getGenres')]
protected string $genre;
}
如果回调是在不同的类中定义的并且是静态的,例如 App\Entity\Genre
,则可以将类名和方法作为数组传递。
1 2 3 4 5 6 7 8 9 10 11
// src/Entity/Author.php
namespace App\Entity;
use App\Entity\Genre;
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
#[Assert\Choice(callback: [Genre::class, 'getGenres'])]
protected string $genre;
}
可用选项
callback
类型: callable|string|null
默认值: null
这是一个回调方法,可以代替 choices 选项来返回选项数组。有关其用法的详细信息,请参见 使用回调函数提供选项。
max
类型: integer
如果 multiple
选项为 true,则可以使用 max
选项来强制最多选择 XX 个值。例如,如果 max
为 3,但输入数组包含 4 个有效项目,则验证将失败。
maxMessage
类型: string
默认值: 您最多只能选择 {{ limit }} 个选项。
这是当用户根据 max 选项选择过多选项时显示的验证错误消息。
您可以在此消息中使用以下参数
参数 | 描述 |
---|---|
{{ choices }} |
可用选项的逗号分隔列表 |
{{ value }} |
当前(无效)值 |
match
类型: boolean
默认值: true
当此选项为 false
时,约束检查给定值不是 choices
选项中定义的值之一。实际上,它使 Choice
约束的行为类似于 NotChoice
约束。
message
类型: string
默认值: 您选择的值不是有效选项。
如果 multiple
选项设置为 false
并且底层值不在有效选项数组中,您将收到此消息。
您可以在此消息中使用以下参数
参数 | 描述 |
---|---|
{{ choices }} |
可用选项的逗号分隔列表 |
{{ value }} |
当前(无效)值 |
min
类型: integer
如果 multiple
选项为 true,则可以使用 min
选项来强制至少选择 XX 个值。例如,如果 min
为 3,但输入数组仅包含 2 个有效项目,则验证将失败。
minMessage
类型: string
默认值: 您必须至少选择 {{ limit }} 个选项。
这是当用户根据 min 选项选择过少选项时显示的验证错误消息。
您可以在此消息中使用以下参数
参数 | 描述 |
---|---|
{{ choices }} |
可用选项的逗号分隔列表 |
{{ value }} |
当前(无效)值 |
multiple
类型: boolean
默认值: false
如果此选项为 true,则输入值应为数组而不是单个标量值。约束将检查输入数组的每个值是否可以在有效选项数组中找到。如果即使一个输入值找不到,验证也会失败。
multipleMessage
类型: string
默认值: 一个或多个给定值无效。
如果 multiple
选项设置为 true
并且正在检查的底层数组上的某个值不在有效选项数组中,您将收到此消息。
您可以在此消息中使用以下参数
参数 | 描述 |
---|---|
{{ value }} |
当前(无效)值 |
{{ label }} |
对应的表单字段标签 |