Laravel 验证必须填写两个字段之一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27875366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:40:18  来源:igfitidea点击:

Laravel Validation one of two fields must be filled

phpvalidationlaravellaravel-4

提问by imperium2335

I have two fields:

我有两个字段:

QQ

QQ

Email

电子邮件

How do I set up a Validator object so that one of these fields must be filled? It doesn't matter which.

如何设置 Validator 对象以便必须填写这些字段之一?哪个都无所谓。



$messages = array(
    'email.required_without:qq' => Lang::get('messages.mustenteremail'),
    'email.email' => Lang::get('messages.emailinvalid'),
    'qq.required_without:email' => Lang::get('messages.mustenterqq'),
);

回答by lukasgeiter

required_withoutshould work.

required_without应该管用。

It means that the field is required if the other field is not present. If have more than two fields and only one is required, use required_without_all:foo,bar,...

这意味着如果其他字段不存在,则该字段是必需的。如果有两个以上的字段并且只有一个是必需的,请使用required_without_all:foo,bar,...

$rules = array(
    'Email' => 'required_without:QQ',
    'QQ' => 'required_without:Email',
);

回答by omarjebari

In the example above (given by lucasgeiter) you actually only need one of the conditions not both.

在上面的例子中(由 lucasgeiter 给出)你实际上只需要一个条件而不是两个。

$rules = array(
    'Email' => 'required_without:QQ'
);

If you have both rules then filling neither in will result in TWO error messages being displayed. This way it will check that at least one field is filled in and will only display one error message if neither are filled.

如果您有这两个规则,那么填写任何一个都将导致显示两条错误消息。这样它会检查是否至少填写了一个字段,如果两者都没有填写,则只会显示一条错误消息。