Isaias
Isaias

Reputation: 347

Using multiple required_if in a validation rule

I have a select with many options, I want another select to be required when the first has an specific value.

    <select id="category" name="category">
            <option value="a">Option A</option>
            <option value="b">Option B</option>
            <option value="c">Option C</option>
            <option value="d">Option D</option>
            <option value="e">Option E</option>
            <option value="f">Option F</option>
    </select>

    <select id="subcategory" name="subcategory">
            <option value="a">Suboption A </option>
            <option value="b">Suboption B </option>
            <option value="c">Suboption C </option>
            <option value="d">Suboption D </option>
            <option value="e">Suboption E </option>
    </select>

I want the second select to be required when the user chooses option a,b or f. Is it correct to use the next rule in the controller code that validates the inputs?:

    $rules = array(
            'category' => 'alpha|in:a,b,c,d,e,f|required|size:1',
            'subcategory' => 'alpha|
                              in:a,b,f|
                              required_if:category,a|
                              required_if:category,b|
                              required_if:category,f|
                              size:1'
    );

Is there (another or) a better way to validate this?

Upvotes: 7

Views: 23755

Answers (2)

MohitMamoria
MohitMamoria

Reputation: 548

Or, you can simply use it like so.

$rules = array('subcategory' => 'required_if:category,a,b,f');

Laravel takes all the parameters except the first one as array and then checks if the value of first parameter is matched with the rest of parameters using in_array method.

Upvotes: 27

The Alpha
The Alpha

Reputation: 146191

You may register a custom validation rule to check this, for example:

Validator::extend('required_if_anyOfThese', function($attribute, $value, $parameters)
{
    // Check here whether any of those Inputs are available and make sure
    // what to do, return true or false depending on the result

    $attribute is field name "subcategory"
    $value will contain the value of the field
    $parameters will contain the parameters, array => a,b,f

});

Use it as:

$rules = array('subcategory' => 'required_if_anyOfThese:a,b,f');

Read more on Laravel Website.

Upvotes: 2

Related Questions