阵列上的Laravel请求验证

阵列上的Laravel请求验证,laravel,validation,request,Laravel,Validation,Request,假设我提交此表格: <form> <input type="text" name="emails[]"> <input type="text" name="emails[]"> <input type="text" name="emails[]"> <input type="text

假设我提交此表格:

<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>
Laravel 7试试这个

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

诚恳地说

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

首先创建一个规则,
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;
 }
那么


不,它“需要”设置所有字段。你在说哪个字段?在您的表单中,我只能看到一个电子邮件字段。
if($email)
如果用户将空格作为值传递,则不会给出正确的结果。这只是示例tho。。替换为你的逻辑…谢谢@ZeroOne。最终解决方案如上所述+'candidate_email'=>[new MinOneArrayFilled],'candidate_email.*'=>['email','nullable']
 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],
 ]);