How to set require if value is chosen in another m

2019-07-24 21:24发布

问题:

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?

回答1:

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.



回答2:

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',
]