【问题标题】:Laravel 6 form array validationLaravel 6 表单数组验证
【发布时间】:2020-05-05 04:54:45
【问题描述】:

我有一个表单,用户可以在其中添加任意数量的联系人。但我陷入了对此的验证。我使用旧的表单验证方式,使用$request->validate 方法。

我的表格(其中一部分是相关的):

<div class="row">
    <div class="col">
        {!! Form::text('contact_name[]', __('site.contact.name'))->placeholder(__('site.contact.name'))->help('<a href="#add-contact" id="add-contact">+ ' . __('site.contact.add_person') . '</a>') !!}
    </div>
    <div class="col">
        {!! Form::text('contact_email[]', __('site.contact.email'))->placeholder(__('site.contact.email')) !!}
    </div>
    <div class="col">
        {!! Form::text('contact_phone[]', __('site.contact.phone'))->placeholder(__('site.contact.phone')) !!}
    </div>
</div>

我的验证是在 CRUD 存储方法中:

$request->validate([
    'contact_name.*' => 'required|max:255',
    'contact_email.*' => 'required|email|max:255',
    'contact_phone.*' => 'required|max:255',
]);

这总是会导致通过,而输入中没有任何内容。 当我尝试以下操作时;它总是失败。

$request->validate([
    'contact_name[]' => 'required|max:255',
    'contact_email[]' => 'required|email|max:255',
    'contact_phone[]' => 'required|max:255',
]);

根据文档,通配符方式是应该的方式。关于如何让它发挥作用的任何想法?

亲切的问候, 尼尔斯

-- 编辑 1--

我的表单请求数据如下所示(仅包括相关变量)

"_token" => "IbYI2FYivl30YJfw8hBHti9bsaBUdkG2T76HZOIN"
"contact_name" => array:1 [▼
    0 => "abc"
]
"contact_email" => array:1 [▼
    0 => "abc"
]
"contact_phone" => array:1 [▼
    0 => "abc"
]

【问题讨论】:

    标签: php laravel validation laravel-6


    【解决方案1】:

    (*) 检查数组中的值,而不是实际数组。如果您添加通配符规则,您将始终获得经过验证的父键。因此,您还必须为每个字段添加一个数组检查:

    'field' =&gt; 'array|required'

    【讨论】:

    • 不幸的是不能工作。数据始终是一个数组。即使发布了 1 个输入。查看第一篇文章,我已经添加了请求数据。
    【解决方案2】:

    像这样更改您的验证

    $request->validate([
        'contact_name'   => "required|array",
        'contact_name.*' => 'required|max:255',
        'contact_email'   => "required|array",
        'contact_email.*' => 'required|email|max:255',
        'contact_phone'   => "required|array",
        'contact_phone.*' => 'required|max:255',
    ]);
    

    在上面的验证中:

    "contact_name" 必须是一个数组。 “contact_name”数组中的值必须是必需的,长度至少为 255 个字符。

    或者

    $request->validate([
        '*.contact_name' => 'required|max:255',
        '*.contact_email' => 'required|email|max:255',
        '*.contact_phone' => 'required|max:255',
    ]);
    

    【讨论】:

    • 不幸的是,这不起作用。为了澄清,我已将请求数据添加到问题中。这对我来说不合逻辑,因为 contact_name.* 会检查 contact_name[0] 和所有以下索引......但它没有。
    猜你喜欢
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2016-08-10
    • 2019-01-24
    • 2017-10-08
    • 2019-08-09
    • 1970-01-01
    • 2016-08-20
    相关资源
    最近更新 更多