验证Laravel 5.7中形式的输入数组 [英] Validate array of inputs in form in Laravel 5.7

查看:43
本文介绍了验证Laravel 5.7中形式的输入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单多次具有相同的输入字段.我的表单字段如下:

My form has the same input field multiple times. My form field is as follows:

<input type='text' name='items[]'>
<input type='text' name='items[]'>
<input type='text' name='items[]'>

请求包含($ request ['items'):

And request contains ($request['items'):

array:1 [▼
  "items" => array:3 [▼
    0 => "item one"
    1 => "item two"
    2 => "item three"
  ]
]

我希望至少填写一项.我当前在控制器中的验证是

I want atleast one of the items to be filled. My current validation in the controller is

    $validator = Validator::make($request->all(),[
        'items.*' => 'required|array|size:1'
    ]);

它不起作用.我尝试使用大小,必需,可为空的组合.什么都行不通.

It does not work. I tried with combination of size, required, nullable. Nothing works.

推荐答案

事实上,它足以使用:

$validator = Validator::make($request->all(),[
        'items' => 'required|array'
    ]);

所做的更改:

  • 使用 items 代替 items.* -如果要使用 items.* ,则要设置常规项目的规则.将规则分别应用于数组的每个已发送元素
  • 删除了 size:1 ,因为这意味着您希望只发送一个元素(并且您至少要发送一个).您完全不需要它,因为您有 required 规则.您可以阅读有关所需规则的文档,并且可以在那里阅读该空数组可能会导致 required 规则失败,因此该array的 required 规则使该数组应至少包含1个元素,因此不需要 min:1 size:1 完全
  • use items instead of items.* - you want to set rule of general items, if you use items.* it means you apply rule to each sent element of array separately
  • removed size:1 because it would mean you want to have exactly one element sent (and you want at least one). You don't need it at all because you have required rule. You can read documentation for required rule and you can read in there that empty array would case that required rule will fail, so this required rule for array makes that array should have at least 1 element, so you don't need min:1 or size:1 at all

这篇关于验证Laravel 5.7中形式的输入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆