陣列驗證

驗證陣列表單輸入欄位非常簡單。

假設你必須驗證給定陣列中的每個名稱,電子郵件和父名稱。你可以執行以下操作:

$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());
}