繁体   English   中英

Laravel填充数组元素的验证规则

[英]Laravel filled validation rule for array element

我需要检查输入的字符串数组,如果数组元素中至少有一个为空,则发出警告。

使用以下规则:

return Validator::make($data, [
    'branches'         => 'array',
    'branches.*'       => 'filled|max:255'
    ]);

但是,似乎填充规则不起作用(而min:1可以正常工作)。 它应该与数组元素一起工作吗?

更新:分支数组不是强制性的,但是如果存在,它应该包含非空元素。

更新:最终在我的验证规则中发现错误。 它看起来像

return Validator::make($data, [
    'branches'         => 'array',
    'branches.*.*'       => 'filled|max:255'
    ]);

因为输入数组是数组的数组。 现在,填充规则可以按我的输入数据正常工作。

使用必填项

return Validator::make($data, [
    'branches'         => 'required|array',
    'branches.*'       => 'required|max:255'
]);

从文档中获取: https : //laravel.com/docs/5.5/validation#available-validation-rules

需要

验证中的字段必须存在于输入数据中,并且不能为空。 如果满足以下条件之一,则该字段被视为“空”:

  • 该值为null
  • 该值为空字符串。
  • 该值是一个空数组或一个空Countable对象。
  • 该值是没有路径的上载文件。

如果仅在存在字段数据的情况下要验证数组,请使用filled 您可以将其与present结合使用。

return Validator::make($data, [
    'branches'         => 'present|array',
    'branches.*'       => 'filled|max:255'
]);

填充

验证中的字段存在时,不能为空。

当下

验证中的字段必须存在于输入数据中,但可以为空。

考虑到您的评论,您应该尝试nullable

return Validator::make($data, [
    'branches'         => 'nullable|array',
    'branches.*'       => 'nullable|max:255'
]);

要么

您可以使用present这将确保应将值或仅空数组作为数组传递

return Validator::make($data, [
    'branches'         => 'present|array',
    'branches.*'       => 'nullable|max:255'
]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM