Laravel验证规则:required_without



我有两个字段:EmailTelephone

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

我试过这个,但它不工作,我需要两个虽然

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

如果两个字段都为空,则产生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时。

最新更新