拉拉维尔in_array验证规则

2022-08-30 16:47:51

我定义了一个数组

$this->allslots=array('10:00:00', '10:10:00', '10:20:00', '10:30:00', '10:40:00', '10:50:00', '11:00:00', '11:10:00', '11:20:00', '11:30:00', '11:40:00', '11:50:00', '12:00:00', '12:10:00', '12:20:00', '12:30:00', '12:40:00', '12:50:00', '13:00:00', '13:10:00', '13:20:00', '13:30:00', '13:40:00', '13:50:00', '14:00:00', '14:10:00', '14:20:00', '14:30:00', '14:40:00', '14:50:00', '15:00:00', '15:10:00', '15:20:00', '15:30:00', '15:40:00', '15:50:00', '16:00:00', '16:10:00', '16:20:00', '16:30:00', '16:40:00', '16:50:00');

现在,我想在将数据保存到数据库之前进行验证,如果给定的输入与上述数组的值之一匹配。为此,我正在做

$this->validate($request, [

        'field' => 'required|in_array:$this->allslots',
    ]);

但是,这将为每个输入返回验证错误。那么,我该怎么做呢?


答案 1

试试这个:

'field' => 'required|in:' . implode(',', $this->allslots),

答案 2

这比公认的答案更具语义性:

use Illuminate\Validation\Rule;

$this->allslots=array('10:00:00', '10:10:00', '10:20:00', '10:30:00', '10:40:00', '10:50:00', '11:00:00', '11:10:00', '11:20:00', '11:30:00', '11:40:00', '11:50:00', '12:00:00', '12:10:00', '12:20:00', '12:30:00', '12:40:00', '12:50:00', '13:00:00', '13:10:00', '13:20:00', '13:30:00', '13:40:00', '13:50:00', '14:00:00', '14:10:00', '14:20:00', '14:30:00', '14:40:00', '14:50:00', '15:00:00', '15:10:00', '15:20:00', '15:30:00', '15:40:00', '15:50:00', '16:00:00', '16:10:00', '16:20:00', '16:30:00', '16:40:00', '16:50:00');

$request->validate([
    'field' => [
        'required',
        Rule::in($this->allslots)
    ]
]);

推荐