Laravel 'sometimes' validator fails with nested arrays

戏子无情 提交于 2019-12-07 07:07:04

问题


Am using the Laravel Validator class to do some basic validation on an array.

My array :

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

I have the validation rules as below:

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

And the custom messages as below :

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

I will use Validator::make($employee, $rules, $messages);

As per my rules, department_name should be validated if and only if it is present in the array. But currently the Validator is not validating department_name when its present and blank. Any ideas what I might be doing wrong?


回答1:


You are going a bit wrong here see the docs here

it is mentioned there If I have $photos['profile'] then my validation will go like this

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

From the above example, In your case it should be like this

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

Since you have array like this $employee['department']['department_name']

So does the $message will go like this

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


来源:https://stackoverflow.com/questions/22892058/laravel-sometimes-validator-fails-with-nested-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!