1

I have a form like this:

<input type="checkbox" name="category[]" value="a">Option A</option>
<input type="checkbox" name="category[]" value="b">Option B</option>
<input type="checkbox" name="category[]" value="c">Option C</option>
<input type="checkbox" name="category[]" value="d">Option D</option>
<input type="checkbox" name="category[]" value="e">Option E</option>
<input type="checkbox" name="category[]" value="f">Option F</option>

<input type="text" name="description">

If option A is chosen, I want to make description required in backend validation in laravel 5. So I tried:

$validator = Validator::make($request->all(), [
        'description' => 'required_if:category,a',
    ]);

if ($validator->fails()) {
        return "error!"
}

However, the checking is not working. How should I set the validation rule to make it works?

cytsunny
  • 4,838
  • 15
  • 62
  • 129

2 Answers2

0

First you need find index of checkbox with value = 'a', in your example is 0 and it can be done by: $index = array_search('a', $request->get('category'));. And finally validation is:

[
    'description' => 'required_if:category.0,a',
]
Marek Skiba
  • 2,124
  • 1
  • 28
  • 31
0

You may try as:

$validator = Validator::make($inputs, [
            'description' => 'required_if:category.0,a',
        ]);

If this doesn't solve your problem then you have to write a custom validator.

Amit Gupta
  • 17,072
  • 4
  • 41
  • 53
  • Well.... this works, but only for option A. If I change to 'required_if:category.1, b', and both option A&B are chosen, it doesn't work. – cytsunny Oct 28 '16 at 10:11