Chris Chris - 3 months ago 17
PHP Question

Laravel 5.2 conditional validation

I initially had fields

first_name
,
last_name
,
password
,
email
as the fields in my sign up form. I need to add an option for signing up as a business.

My initial validation rules:

protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}


I need to add a
business_name
field. I need the validation to be:

first_name
and
last_name
are required xor
business_name
is required.

How can I do this in Laravel 5.2? I was looking at the
sometimes
rule - but I'm not sure if that is how this should be done.

edit:

I suppose it could almost be accomplished via:

protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'sometimes|max:255',
'last_name' => 'sometimes|max:255',
'business_name'=>'sometimes|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}


Although from my understanding of the
sometimes
rule, it will only validate if the key is present in the input array, therefore
first_name
could be present, and
last_name
could be non-existent which would would still validate as a "pass". This isn't the behavior that I'd like.

Answer

What you might be looking for is the required_without:foo,bar,...

That validation rule says 'The field under validation must be present and not empty only when any of the other specified fields are not present'.

So you might have business_name => required_without:first_name,last_name

Comments