【问题标题】:Custom Validation Message in LaravelLaravel 中的自定义验证消息
【发布时间】: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 次。

标签: php laravel laravel-5


【解决方案1】:

您只需要一个字段上的规则即可使其正常工作。最简单的方法是创建一个空字段并将规则应用于它。该字段不必存在于数据库架构或应用程序中的任何其他位置。

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',
    ),
),

现在,当所有字段(或您的情况下的复选框)为空时,您将收到错误消息。填写一个或多个就不会出错了。

【讨论】:

    【解决方案2】:
    if(!valiate){
      return redirect()->back()->withError('Some Fields are Required');
    }
    

    【讨论】:

    • 这个答案有什么问题,如果您不满意,请添加评论。
    • 我认为拼写错误:p
    【解决方案3】:
    $messages = [
        'required_without_all' => 'The :attribute field is required.',
    ];
    
    $validator = Validator::make($input, $rules, $messages);
    

    【讨论】:

    • 正如我已经说过的 - 我会更新我的问题 - 这仍然会输出五个错误消息,我只想要一个。不过谢谢
    猜你喜欢
    • 2014-05-31
    • 2017-06-28
    • 2017-12-13
    • 2020-07-18
    • 2019-11-01
    • 1970-01-01
    • 2016-01-29
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多