Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 762
Isaias Avatar asked Mar 11 '14 21:03

Isaias


2 Answers

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.

like image 58
MohitMamoria Avatar answered Sep 29 '22 16:09

MohitMamoria


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.

like image 31
The Alpha Avatar answered Sep 29 '22 15:09

The Alpha