required_without 不适用于其他规则

required_without not working with other rules

'person.mail' =>'required_without:person.phone|sometimes|email|unique:persons,mail',

'person.phone' => 'required_without:person.mail|sometimes|regex:/[0-9]/|size:10|unique:persons,phone'

我需要验证 phone 和邮件,其中一项是强制性的

当邮件为空而 phone 不为空时,电子邮件规则的验证失败,这是双向的,当邮件存在且 phone 为空时,验证失败正则表达式规则

如果值为空,我如何停止验证?

作为 laravel docs 状态:

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list.

我感觉你实际上 post 同时 person[email]person[phone],在这种情况下 sometimes 将指示验证继续,因为值将随后是空字符串(或者可能 null)而不是 不存在 。您可以有条件地在其他断言上添加规则,而不是 通过创建您自己的验证器检查密钥 x 是否存在 ,并使用它的 sometimes() 方法来创建您自己的断言:

$v = Validator::make($data, [
    'person.email' => 'email|unique:persons,mail',
    'person.phone' => 'regex:/[0-9]/|size:10|unique:persons,phone',
]);

$v->sometimes('person.email', 'required', function($input) {
    return ! $input->get('person.phone');
});

$v->sometimes('person.phone', 'required', function($input) {
    return ! $input->get('person.email');
});

此处的区别在于字段默认 不是必需的。因此,例如,person.phone 可能为空,或者必须与您的正则表达式匹配。如果 $input->get('person.email') returns 一个 falsy 值,毕竟 person.phone 是必需的。

请注意,我认为您的正则表达式有误。只要 person.phone 中的任何字符是数字,它就会通过。我认为您正在寻找这样的东西:

'person.phone' => 'regex:/^[0-9]{10}$/|unique:persons,phone'

我是这样解决的,这不是最好的方法,但效果很好 验证后我添加了

if(empty($request->all()['person']['mail']) && empty($request->all()['person']['phone'])){
        $validator->errors()->add('person.mail', 'Mail or phone required');
        $validator->errors()->add('person.phone', 'Mail or phone required');
        return redirect("admin/people-create")->withInput()->withErrors($validator);
    }