数组验证
验证数组表单输入字段非常简单。
假设你必须验证给定数组中的每个名称,电子邮件和父名称。你可以执行以下操作:
$validator = \Validator::make($request->all(), [
'name.*' => 'required',
'email.*' => 'email|unique:users',
'fatherName.*' => 'required'
]);
if ($validator->fails()) {
return back()->withInput()->withErrors($validator->errors());
}
Laravel 显示验证的默认消息。但是,如果要为基于阵列的字段定制消息,可以添加以下代码:
[
'name.*' => [
'required' => 'Name field is required',
],
'email.*' => [
'unique' => 'Unique Email is required',
],
'fatherName.*' => [
'required' => 'Father Name required',
]
]
你的最终代码如下所示:
$validator = \Validator::make($request->all(), [
'name.*' => 'required',
'email.*' => 'email|unique:users',
'fatherName.*' => 'required',
], [
'name.*' => 'Name Required',
'email.*' => 'Unique Email is required',
'fatherName.*' => 'Father Name required',
]);
if ($validator->fails()) {
return back()->withInput()->withErrors($validator->errors());
}