54

I have a 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 the following 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 is still required. Why? How can I fix it?

0

5 Answers 5

79

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

$rules = array(
      'selection' => 'required',
      'stext'     => 'required_if:selection,2,3'
);
1
  • 1
    The same can be used for required_unless. Commented Jun 29, 2023 at 12:13
73

EDIT: As pointed out by LePhleg answer, there is a nicest syntax for this validation:

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

Old answer below:

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.

2
5

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

1

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'
   );
   $validate = \Validator::make($input,$rule);
$validator->sometimes('stext', 'required', function($input){
    return (($input->selection == 1) || ($input->selection == 2));
});
}
0
0

You can always use the Rule class to override the default behavior. This should work in case of multiple values:

use Illuminate\Validation\Rule;
..................    
'stext' => Rule::requiredIf(function ()  {
                return in_array(request()->selection,[2,3]);
            }),

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.