Laravel'有时'验证失败,嵌套数组

时间:2014-04-06 09:15:18

标签: php laravel laravel-validation

使用Laravel Validator类对数组进行基本验证。

我的阵列:

$employee['name']='name';
$employee['address']='address';
$employee['department']['department_name']='deptname';
$employee['department']['department_address']='deptaddress';

我的验证规则如下:

$rules = array(
    'name'=> 'required',
    'address' => 'required',
    'department.department_name' => 'sometimes|required'
)

自定义消息如下:

$messages = array(
     'name.required' => 'Employee Name is required',
     'address.required' => 'Address is required'
     'department.department_name.required' => 'Department name is required'
)

我将使用Validator::make($employee, $rules, $messages);

根据我的规则,当且仅当数组中存在department_name时,才应验证Validator。但目前department_name目前尚未验证{{1}}并且空白。我可能做错了什么想法?

1 个答案:

答案 0 :(得分:1)

你这里有点不对,请看docs这里

在那里提到如果我有$photos['profile']那么我的验证将会像这样

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

从上面的例子中,在你的情况下它应该是这样的

$rules = array(
    'name'=> 'required',
    'address' => 'required',
    'employee.department.department_name' => 'sometimes|required'
)

因为你有这样的数组$employee['department']['department_name']

$message也是这样的

$messages = array(
     'name.required' => 'Employee Name is required',
     'address.required' => 'Address is required'
     'employee.department.department_name.required' => 'Department name is required'
)