How to set require if value is chosen in another m

2019-07-24 20:59发布

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?

2条回答
贼婆χ
2楼-- · 2019-07-24 21:20

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.

查看更多
Lonely孤独者°
3楼-- · 2019-07-24 21:20

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',
]
查看更多
登录 后发表回答