我有两个字段:Email
和 Telephone
我想创建一个验证,其中需要两个字段之一,如果设置了一个或两个字段,它应该是正确的格式。
我试过了,但是没用,不过我两个都需要
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
时。
https://stackoverflow.com/questions/69676375/