'Email OR Phone validation in Laravel 5.4

I want to know how to validate Email or Phone. I want to create an API for sending OTP. Suppose I have one input field verify_by (which is an email or phone). How to validate using validator in Laravel 5.4?

  protected function validator(array $data)
  {
    return Validator::make($data, [
        'verify_by' => 'required',     
    ]);
  }

I used only required but I want email and phone validation.



Solution 1:[1]

You have to create custom validator (read the docs).

public function boot()
{
    Validator::extend('mailorphone', function ($attribute, $value, $parameters, $validator) {
        // your logic here. Return true if validated and false if not
        return true;
    });
}

Then add this rule into the set of rules:

return Validator::make($data, [
    'verify_by' => 'required|mailorphone',     
]);

Solution 2:[2]

Custom Validation rule for verifying the field to be either an email or phone:

// App\Providers\AppServiceProvider::boot 

Validator::extend('email_or_phone', function ($attribute, $value, $parameters, $validator) {
   if( $validator->validateEmail($attribute, $value, []) ) {
       return true;
   }

   return $validator->validateDigitsBetween($attribute, $value, [8, 12]);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shukshin.ivan
Solution 2 Sumit Wadhwa