Laravel 'sometimes' validator fails with n

2019-05-06 17:19发布

问题:

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'
)