【问题标题】:Laravel request validation on arrayLaravel 请求数组验证
【发布时间】:2021-02-15 22:40:27
【问题描述】:

假设我提交了这个表单:

<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>

然后我如何验证$request-&gt;emails[] 中至少有一个(任何人)已填满?

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

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

Laravel 7

【问题讨论】:

    标签: laravel validation request


    【解决方案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],
     ]);
    

    【讨论】:

    • 如果用户将空格作为值传递,if($email) 将不会给出正确的结果
    • 这只是一个例子。用你的逻辑替换..
    • 感谢@ZeroOne。最终解决方案如上 + 'candidate_email' => [new MinOneArrayFilled], 'candidate_email.*' => ['email', 'nullable']
    【解决方案2】:

    试试这个

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

    真诚的

    【讨论】:

    • 不——它“要求”设置所有字段。
    • 你在说哪个领域?我只能在您的表单中看到一个电子邮件字段。
    猜你喜欢
    • 2020-09-04
    • 2020-06-28
    • 2020-09-11
    • 1970-01-01
    • 2017-11-21
    • 2020-01-13
    • 1970-01-01
    • 2016-08-10
    • 2017-10-01
    相关资源
    最近更新 更多