Using Form Request Validation (preferably), is there a way to validate more than one field simultansously?
For example, suppose you have two fields: firstname and lastname, each with their own validation rules.
Suppose that each have a max chars rule of 20 (max:20)
But, you don't want firstname and lastname combined to have more than 30 chars.
How would you go about this?
Not sure if there is something out of the box for that, but you could create your own rule, use a closure, or use sometimes, see Complex Conditional Validation. You can access other fields using the request() helper, sometimes already provides access to other values through the parameter input.
The field has to exist in the data that is passed to the validator, that's all. It can come from a request's payload, be made up on the fly, whatever ... Is fullname included in the request? Then you are fine. It doesn't have to exist in any model or database if that's what you are concerned about. I'm testing my custom validators with arbitrary fields all the time.
If you do data.append("fullname", firstname + " " + lastname); and then submit that data on the Javascript side, fullname is already in the request's data. No need to do it on the PHP side again.
To me, that just seems unnecessary. It's really easy to just create a custom rule that can do that validation, plus if you need to do the same kind of validation on another request, you don't have to duplicate logic now.
We are running around in circles ... Did you even try what I've already proposed?
For example in the rules() method of your form request:
return [
'firstname' => [function($attribute, $value, $fail) {
if (request()->has('lastname') && ! empty(request('lastname'))) {
// do your validation here when both fields are present, e.g. both strings are max 30 chars
} else {
// do your validation here when just the first name is present, e.g. string is max 20 chars
}
}],
'lastname' => 'max:20',
];
No problem, just let us know when there is something you don't understand or it is not clear to you how to apply something. It's hard to know what's going on in your mind or what exactly is causing trouble :-)