Laravel请求数组验证

时间:2020-11-03 09:04:16

标签: laravel validation request

让我说我提交这份表格:

<form>
    <input type="text" name="emails[]">
    <input type="text" name="emails[]">
    <input type="text" name="emails[]">
    <input type="text" name="emails[]">
    <input type="text" name="emails[]">
</form>

然后我如何验证至少{strong> 1个(所有人)中的$request->emails[]是否已填充?

我已经尝试过-但是它不起作用:

 $request->validate([
     'emails' => 'array|min:1',
     'emails.*' => 'nullable|email',
 ]);

Laravel 7

2 个答案:

答案 0 :(得分:1)

尝试一下

$request->validate([
    'emails' => 'array|required',
    'emails.*' => 'email',
]);

私下

答案 1 :(得分:1)

为满足您的要求,您可能需要自定义规则

首先创建一个规则,php artisan make:rule YourRuleName

YourRuleName.php

 public function passes($attribute, $value)
 {
     foreach(request()->{$attribute} as $email) {
         // if not null, then just return true. 
         // its assume in arrays some item have values
         if ($email) { // use your own LOGIC here
             return true;
         }
     }

     return false;
 }

然后

 $request->validate([
     'emails' => [new YourRuleName],
 ]);