Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 368
1221312 Avatar asked Nov 29 '25 15:11

1221312


1 Answers

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

like image 168
Daniel Verem Avatar answered Dec 01 '25 04:12

Daniel Verem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!