Laravel 验证规则:required_without

Laravel Validation rules: required_without

我有两个字段:EmailTelephone

我想创建一个验证,其中需要两个字段之一,如果设置了一个或两个字段,它应该是正确的格式。

我试过了,但是没用,不过我两个都需要

 public static array $createValidationRules = [
        'email' => 'required_without:telephone|email:rfc',
        'telephone' => 'required_without:email|numeric|regex:/^\d{5,15}$/',

    ];

如果两个字段都为空,则产生 required_without 错误消息是正确的。这个错误信息很清楚的说,如果另一个没有,则必须填写该字段。如果需要,您可以change留言:

$messages = [
    'email.required_without' => 'foo',
    'telephone.required_without' => 'bar',
];

但是,您必须添加 nullable 规则,因此格式规则在字段为空时不适用:

$rules = [
    'email' => ['required_without:telephone', 'nullable', 'email:rfc'],
    'telephone' => ['required_without:email', 'nullable', 'numeric', 'regex:/^\d{5,15}$/'],
];

此外:It is recommended 将规则写成数组,尤其是在使用 regex.