4

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?

5
  • 1
    I sent pull request to the framework, so when accepted I'll leave you a comment Commented Apr 6, 2014 at 20:57
  • it has been months since this bug was pointed out..and fixed. hopefully your pr will be accepted soon @dezco. thank you Commented Jun 18, 2014 at 3:06
  • also documentation is wrong on how to implement the sometimes rule as it indicates to use sometimes|required, but required take precedence and makes sometimes pointless. Commented Jun 18, 2014 at 3:30
  • In 4.1.* this error still occurs. @JarekTkaczyk, can you post the pull request? Commented May 14, 2016 at 23:51
  • @AlwinKesler I guess this was the one github.com/laravel/framework/pull/4076 Commented May 16, 2016 at 1:52

1 Answer 1

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'
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.