【问题标题】:Laravel Validation of two combined columns两个组合列的Laravel验证
【发布时间】:2020-10-05 15:54:47
【问题描述】:

我是 Laravel 的新手,我需要一些验证方面的帮助。我有两个字段,一个是国家代码,另一个是电话号码,它们分别存储在数据库的相应列中。我想将电话号码验证为唯一电话(1234567)。我怎样才能做到这一点?

这是我的自定义表单请求的验证规则方法

public function rules()
{
    return [
        'first_name' => 'required|string',
        'last_name' => 'required|string',
        'email' => ['required', Rule::unique('clients')->ignore($this->client)],
        'country_code' => 'required',
        'phone' => ['required',Rule::unique('clients')->ignore($this->client)],
        'receive_video_lessons' => 'required|boolean'
    ];
}

【问题讨论】:

    标签: laravel validation


    【解决方案1】:

    您可以使用自定义规则。试试这样的:

    public function rules()
        {
            return [
                'first_name' => ['required', 'string'],
                'last_name' => ['required', 'string'],
                'email' => ['required', Rule::unique('clients')->ignore($this->client)],
                'country_code' => ['required'],
                'phone' => ['required', new IsValidPhoneNumber($this->country_code, $this->client)],
                'receive_video_lessons' => 'required|boolean'
            ];
        }
    

    然后在您的自定义验证规则中:

    class IsValidPhoneNumber implements Rule
    {
        protected $countryCode;
        protected $clientId;
    
        public function __construct($countryCode, $clientId)
        {
            $this->countryCode = $countryCode;
            $this->clientId = $clientId;
        }
    
        public function passes($attribute, $value)
        {
            return ! Client::where('country_code', $this->countryCode)
                ->where('phone', $value)
                ->where('client_id', '!=', $this->clientId)
                ->exists();
        }
    
        public function message()
        {
            return 'This :attribute is not valid.';
        }
    }
    
    

    你可能需要按摩它才能工作,但你明白了。

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 2020-10-31
      • 2020-06-10
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      相关资源
      最近更新 更多