如何验证 Laravel 中的输入与一个或多个精确值匹配?

问题描述 投票:0回答:2

Laravel 中的验证类是否验证确切的单词?

例如

$rules = [
    "field" => "hello"
]

该字段的值必须是“hello”。

php laravel laravel-validation
2个回答
56
投票

是的。我知道至少有两种方法。

// option one: 'in' takes a comma-separated list of acceptable values
$rules = [
    'field' => 'in:hello',
];

// option two: write a matching regular expression
$rules = [
    'field' => 'regex:^hello$',
];

实际上,我不记得正则表达式中是否需要 ^$ 分隔符,但是通过尝试很容易找到。 :)


7
投票

Laravel 5.5 更新了方法。 https://laravel.com/docs/5.5/validation#rule-in

// 'in' takes an array of values

$rules = [
    'field' => [ Rule::in('hello')]
];
控制器中的

Use Rule;
命名空间用于访问规则类
(Illuminate\Validation\Rule)

© www.soinside.com 2019 - 2024. All rights reserved.