Search code examples
phplaravelvalidationphp-8laravel-9

Laravel validation rule for one item which can be email or phone number


I want to validate one request item which can be phone number or email address. Is there any way in Laravel validation rules or other options to handle this?

<?php

namespace App\Http\Requests\UserAuthRequests;

use Illuminate\Foundation\Http\FormRequest;

class AuthenticationUser extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'credentials' => ['required'],
            'g-recaptcha-response' => ['required'],        ];
    }
}

Solution

  • My proposition is to write custom validation rule, where you will be conditionally check if it is a valid email or phone number.

    Validator::extend('email_or_phone', function ($attribute, $value, $parameters, $validator) {
       return 
           $validator->validateDigitsBetween($attribute, $value, [8, 10]) ||
           $validator->validateEmail($attribute, $value, []);
    });
    

    Write this code in boot method in for example AppServiceProvider. I also strongly recommend you to use dedicated classes for custom rules as described here: https://laravel.com/docs/9.x/validation#custom-validation-rules

    In both ways you just end up with code like this:

    public function rules()
    {
        return [
            'credentials' => ['email_or_phone'], // HERE WE USE OUR CUSTOM RULE
            'g-recaptcha-response' => ['required'],        
        ];
    }