Laravel 一项可以是电子邮件或 phone 号码的验证规则

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

我想验证一个请求项,可以是 phone 号码或电子邮件地址。 Laravel 验证规则或其他选项中有什么方法可以处理这个问题吗?

<?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'],        ];
    }
}

我的建议是编写自定义验证规则,您将有条件地检查它是否是有效的电子邮件或 phone 号码。

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

例如AppServiceProvider中的boot方法中写这段代码。我还强烈建议您使用专用 类 作为自定义规则,如下所述:https://laravel.com/docs/9.x/validation#custom-validation-rules

在这两种方式中,您最终都会得到如下代码:

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