我需要一条错误消息,该错误消息的内容为:“您需要至少在多个下拉列表中选中至少一个框”
我的五个下拉菜单分别是:国家/地区,县,戈尔,Locauth,Parlc。
到目前为止,我的 Controller 是;
$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);
但这只会给我五个错误消息,而不是一个。
最佳答案
您只需要在一个字段上使用该规则即可使其正常工作。最简单的方法是创建一个空字段并将规则应用于该字段。该字段不必存在于数据库模式或应用程序中的其他任何位置。
public static $rules = [
location => required_without_all:country,county,gor,locauth,parlc
];
然后在您的语言文件中自定义消息。
'custom' => array(
'location' => array(
'required_without_all' => 'At least one location field is required',
),
),
现在,当所有字段(或您的情况下的复选框)为空时,您将收到错误消息。如果填写了一个或多个,则不会有任何错误。
关于php - Laravel中的自定义验证消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29828017/