Thursday, March 16, 2017

Laravel validation required_without

Is there a way to do this validation just by using out of the box laravel's validation rules? I know custom validation rules but i think this is a classic case and it could have a ready to use solution.

I have a contact form with a email field and a phone field, so i want the user to fill at least one of these fields and when the form is submitted the validator must check if 'email' is a correct email adress and if 'phone' is a correct phone number.

The rules i used in my request for validation:

public function rules()

    {
        return [
            'email' => 'required_without:phone|email',
            'phone' => 'required_without:email|digits_between:5,12',
        ];
    }

What i want:

  • If a correct email and a correct phone are given (Succeed)
  • if a correct email and an empty phone are given (Succeed)
  • if a correct phone and an empty email are given (Succeed)
  • If both are empty or if one of the fields is given but wrong (fail)

What i get:

  • If a correct email and a correct phone are given (Succeed)
  • if a correct email and an empty phone are given (validation fails and asks me to give a correct phone)
  • if a correct phone and an empty email are given (validation fails and asks me to give a correct email)
  • If both are empty or if one of the fields is given but wrong (fail)


via Evrard-c

Advertisement