php – Laravel中的自定义验证消息

前端之家收集整理的这篇文章主要介绍了php – Laravel中的自定义验证消息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要一条错误消息,基本上说“你需要在至少一个多下拉列表中检查至少一个方框”

我的五个多下拉名称是;国家,县,Gor,Locauth,Parlc.

到目前为止我的控制器是;

$rules = Array
(
  [country] => required_without_all:county,gor,locauth,parlc
  [county] => required_without_all:country,parlc
  [gor] => required_without_all:country,county,parlc
  [locauth] => required_without_all:country,parlc
  [parlc] => required_without_all:country,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,parlc
];

然后在您的语言文件自定义消息.

'custom' => array(
    'location' => array(
        'required_without_all' => 'At least one location field is required',),

现在,当所有字段(或您的案例中的复选框)都为空时,您将收到错误消息.如果填写了一个或多个,则不会有任何错误.

猜你在找的Laravel相关文章