【问题标题】:Customizing validation error message for a custom validation rule in laravel在 laravel 中为自定义验证规则自定义验证错误消息
【发布时间】:2021-03-23 19:42:16
【问题描述】:

在我的控制器中,我正在尝试为自定义验证规则自定义错误消息。问题是自定义规则没有名称,因此我在自定义此规则的错误消息时遇到了一些困难。

Controller.php

$request->validate([
    "address.house" => ['bail', 'string', 'nullable', 'max:100', new CustomRule]
],
[
    "address.house.hereWillBeTheNameOfCustomRule" => "Custom message for custom rule"
]);

CustomRule.php

public function message()
{
    return "I want to override this message.";
}

【问题讨论】:

  • 告诉我您是否在 CustomRule 类中定义了message() 方法?或者您可以在索引为“custom_rule”的resources/lang/en/validation.php 文件中添加消息。
  • 我已经定义了消息方法。我想覆盖该消息。

标签: laravel laravel-8


【解决方案1】:

确保您已在 CustomRule 类中定义 message() 方法以返回验证消息,例如

public function message()
{
    return 'The :attribute must be match custom rule.';
}

或 可以将自定义验证消息添加到索引为“custom_rule”的resources/lang/en/validation.php 文件,例如

'custom_rule' => 'The :attribute must be match custom rule.'

如果您想在运行时使用自定义消息,请按如下方式使用:

'address.house.custom_rule' => 'The :attribute must be match custom rule'

更多详情请查看 laravel 文档:https://laravel.com/docs/8.x/validation#using-rule-objects 希望对您有意义,如果仍有任何疑问,请随时询问。

【讨论】:

  • 在“address.house.custom_rule”中,“custom_rule”是自定义规则的名称,对吧?这个名字怎么设置?
  • 是的! 'custom_rule' 是自定义规则的名称,我从您的规则类名称中猜到了这一点,即CustomRule。如果您有不同的验证规则类名,则只需使用下划线 (_) 拆分类名单词即可获得规则名称。
  • 您得到的结果或错误是什么?
  • 我收到“我想覆盖此消息”。作为验证错误消息。但我想要“自定义规则的自定义消息”作为验证错误消息。
  • 您能否尝试覆盖任何其他验证消息(只是为了确认,其他一切都按方面工作 - 调试)。假设max 规则:```[“address.house.max”=>“我的自定义最大规则”]```
猜你喜欢
  • 2015-09-07
  • 2016-10-21
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2018-04-30
  • 2021-08-30
  • 2012-03-24
  • 1970-01-01
相关资源
最近更新 更多