Laravel in_array验证规则

时间:2016-08-10 20:50:25

标签: php validation laravel

我已经定义了一个数组

$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',
    ]);

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

4 个答案:

答案 0 :(得分:29)

试试这个:

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

这会给你预期的结果吗?

答案 1 :(得分:12)

这比接受的答案更具语义性:

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)
    ]
]);

答案 2 :(得分:0)

我找到了更好的解决方案。 validate in_array期望该数组是请求中的参数之一。如果数组中有逗号,则接受的答案将不起作用。要使用in_array而不需要创建新规则,只需执行以下操作:

$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['allslots'] = $this->allslots;

validate($request, [

        'field' => 'required|in_array:allslots.*',
    ]);

确保在末尾添加。*

答案 3 :(得分:0)

考虑添加:

use Illuminate\Validation\Rule; 

如此处所示:http://www.javaear.com/question/45810009.html