【发布时间】:2015-04-23 15:31:05
【问题描述】:
我需要一条错误消息,基本上说“您需要在至少一个多下拉菜单中选中至少一个框”
我的五个多下拉名称是; Country, County, Gor, Locauth, Parlc.
到目前为止,我的控制器是;
$rules = Array
(
[country] => required_without_all:county,gor,locauth,parlc
[county] => required_without_all:country,gor,locauth,parlc
[gor] => required_without_all:country,county,locauth,parlc
[locauth] => required_without_all:country,county,gor,parlc
[parlc] => required_without_all:country,county,gor,locauth
)
$validator = \Validator::make($input, $rules);
我的问题是我看不到只返回一个规则的方法。它返回 5 个非常相似的措辞规则;
The country field is required when none of county / gor / locauth / parlc are present.
The county field is required when none of country / gor / locauth / parlc are present.
The gor field is required when none of country / county / locauth / parlc are present.
The locauth field is required when none of country / county / gor / parlc are present.
The parlc field is required when none of country / county / gor / locauth are present.
不精彩!有没有办法只返回一条自定义消息?
--- 编辑 ---
我应该添加... 上面的Array() 代码不是实际代码,它是创建这些规则的实际代码的 print_r 结果。我只是认为这会使阅读和理解我的问题更容易。实际的代码,如果你有兴趣的话;
$fields = ['country','county','gor','locauth','parlc'];
$rules = [];
foreach ($fields as $i => $field) {
$rules[$field] = 'required_without_all:' . implode(',', array_except($fields, $i));
}
--- 另一个编辑 ---
我已经知道自定义错误消息,例如:
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
但这只会给我五个错误消息,而不是只有一个。
【问题讨论】:
-
查看文档laravel.com/docs/5.0/validation#custom-error-messages。可以设置每个字段的验证消息。
-
它不只是打印出 5 条自定义错误消息吗?我只想要一个捕获所有五个...
-
你为什么使用
foreach?最好把整个代码贴出来 -
我不明白,如果你只想要一条错误消息,为什么你有 5 条规则?你为什么不创建一个验证规则来测试你的五个输入?而不是手动验证每一个?
-
因为我必须将每个字段与其他 4 个字段进行比较。我认为最好的方法是
required_without_all。你不能只用一条规则来做到这一点——可以吗?你必须这样做 5 次。