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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With