验证数组表单输入字段非常简单。
假设您必须验证给定数组中的每个姓名,电子邮件和父亲姓名。您可以执行以下操作:
$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()); }