首页 > 解决方案 > Laravel 验证规则:required_without

问题描述

我有两个领域:EmailTelephone

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

我试过这个,但它不起作用,我需要两个

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

    ];

标签: phplaravelvalidation

解决方案


如果两个字段都为空,则两个字段都产生required_without错误消息是正确的。此错误消息清楚地表明,如果另一个不是,则必须填写该字段。如果需要,您可以更改消息:

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

此外:建议将规则编写为数组,尤其是在使用regex.


推荐阅读