use*_*668 5 php arrays validation laravel
我需要检查输入的字符串数组,如果至少一个数组元素为空,则发出警告。
使用以下规则:
return Validator::make($data, [
'branches' => 'array',
'branches.*' => 'filled|max:255'
]);
Run Code Online (Sandbox Code Playgroud)
然而,填充规则似乎不起作用(而 min:1 工作正常)。它是否应该与数组元素一起使用?
更新: 分支数组不是强制性的,但如果存在,它应该包含非空元素。
更新: 终于在我的验证规则中发现了错误。它应该看起来像
return Validator::make($data, [
'branches' => 'array',
'branches.*.*' => 'filled|max:255'
]);
Run Code Online (Sandbox Code Playgroud)
因为输入数组是数组的数组。现在填充的规则可以按照我的输入数据的预期工作。
使用必需的代替
return Validator::make($data, [
'branches' => 'required|array',
'branches.*' => 'required|max:255'
]);
Run Code Online (Sandbox Code Playgroud)
来自文档: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'
]);
Run Code Online (Sandbox Code Playgroud)
填充
验证字段存在时不得为空。
展示
验证字段必须存在于输入数据中,但可以为空。