Lets say I have a form like this:
(The O's represent checkbox input)
O - Pizza option O - Free beer with pizza O - I want extras on my pizza ---- O - cheese ---- O - funghi ---- O - ham ---- O - something else
User can select pizza and free beer, but also some extras. Out of these extras he needs to chose at least one ingredient but only if extra option is selected.
My validation is as follows:
'extras.cheese' => 'required_without_all:funghi,ham,something_else',
'extras.funghi' => 'required_without_all:cheese,ham,something_else',
'extras.ham' => 'required_without_all:cheese,funghi,something_else',
'extras.something_else' => 'required_without_all:cheese,funghi,ham',
However I want these to apply only if extraOption
is selected. In other words I want to nest these rules inside of required_if:extraOption,1
rule.
EDIT:
I guess I need a custom validator that will look something like:
'extras.cheese' => 'required_if_then_required_without_all:extraOption,funghi,ham,something_else'
where the first option will go to the required_if
part of the function, and rest of the options to required_without_all
part.
I will edit my question as I move along.
EDIT 2:
Following the documentation (http://laravel.com/docs/5.1/validation#custom-validation-rules) I added code below to app/Providers/AppServiceProvider.php
Validator::extend('required_if_then_required_without_all', function($attribute, $value, $parameters) {
return true;
});
Now I need to figure out what is what and how to implement the logic.
EDIT3:
This is what I thought should work but it doesn't. It always passes validation.
Validator::extend('required_if_then_required_without_all', function($attribute, $value, $parameters) {
$required_if = $parameters[0];
$required_without_all = array_except($parameters, [0]); // remove entry with key 0 from $parameters array
$value = false;
if($required_if != 1)
{
$value = true;
}
else
{
foreach ($required_without_all as $r)
{
if ( $r == 1) { $value = true; }
}
}
return $value;
});
And I call it as:
'cheese' => 'required_if_then_required_without_all:extraOption,funghi,ham,something_else',
UPDATE ON EDIT3:
Adding new validator as:
Validator::extend('false', function($attribute, $value, $parameters) {
return false;
});
And calling it as 'cheese' => 'false',
does nothing. I guess I'm doing something very wrong here and any help is appreciated.
2nd UPDATE TO EDIT3:
I think the problem is that Form::checkbox
doesn't send any data if not selected so the validation is not triggered.
Calling false
on Form::text
works as excepted.
3rd UPDATE TO EDIT3:
Adding
{!! Form::hidden('cheese',0) !!}
before the checkbox made the field responsive to false
Validator. But the required_if_then_required_without_all
validator still doesn't get triggered.
Structure:
Validator
which is applied to
extraOption
likeThe Checkboxes are: