Required_if laravel with multiple value

2019-06-14 23:59发布

i have dropdown menu like this

<select name="selection">
   <option value="1">Option 1</option>
   <option value="2">Option 2</option>
   <option value="3">Option 3</option>
</select>
<input type="text" name="stext">

i want in laravel

public static myfunction(){
   $input = \Input::only('selection','stext');
   $rule = array(
      'selection' => 'required',
      'stext' => 'required_if:selection,2,3',
   );
   $validate = \Validator::make($input,$rule);
}

but if i select option 1, stext still required. why? how i can fix it?

thanks before.

4条回答
相关推荐>>
2楼-- · 2019-06-15 00:12

You just have to pass all the values as parameters separated by comma:

$rules = array(
      'selection' => 'required',
      'stext'     => 'required_if:selection,2,3'
);
查看更多
做自己的国王
3楼-- · 2019-06-15 00:22

try this one

if single match value then used like that

'stext'     => 'required_if:selection,2'

if you have multiple value then used like that (separated by comma)

'stext'     => 'required_if:selection,2,3'

for more information see documentation required_if

查看更多
爷、活的狠高调
4楼-- · 2019-06-15 00:23

You can go ahead with sometimes validation for laravel. you can define a custom closure as in the below example

public static myfunction(){
   $input = \Input::only('selection','stext');
   $rule = array(
      'selection' => 'required'
   );
$validator->sometimes('stext', 'required', function($input){
    return (($input->selection == 1) || ($input->selection == 2));
});
   $validate = \Validator::make($input,$rule);
}
查看更多
淡お忘
5楼-- · 2019-06-15 00:30

I think that the require_if validation accept only one value per time. Try to change your validation code as below:

$rule = array(
  'selection' => 'required',
  'stext' => 'required_if:selection,2|required_if:selection,3',
);

EDIT: Check LePhleg answer, is more cleaner. At the time of the answer that was not possible, just check the question, he was using the same method but not worked.

查看更多
登录 后发表回答