I'm using Laravel 5's Form Request Validation feature to validate a form input.
In my form, I have 2 fields num_adults
and num_children
.
I need to ensure that the sum of both fields do not exceed a certain value.
What I've tried is in the rules()
function of my validation file, I used merge()
to artificially add a new input value that is the sum of both num_adults
and num_children
.
$this->merge([
'max_persons' => $this->input('num_adults') + $this->input('num_children')
]);
And then in the rules array returned,
$rules = [
'num_adults' => 'integer|max:2',
'num_children' => 'integer|max:1',
'max_persons' => 'integer|max:2',
];
The validation works fine for num_adults
and num_children
. But max_persons
seems to be ignored.
I might skip the array merge and have my rules like:
$rules = [
'num_adults' => 'integer|max:'.(2-$this->get('num_children', 0)) ,
'num_children' => 'integer|max:'.(2-$this->get('num_adults', 0))
];
2 being the maximum permitted value.
On the other hand, the approach that you've started gives you a little more flexibility on the error messages.
The validator already has the values before you update the array, so it doesn't know about your addition. You could add a validator method to your request object to merge in your values a little earlier in the process.
public function validator(Factory $factory)
{
$this->merge([
'max_persons' => $this->input('num_adults') + $this->input('num_children')
]);
return $factory->make(
$this->all(),
$this->rules(),
$this->messages()
);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments