在 laravel 中为自定义验证规则自定义验证错误消息

时间:2021-03-23 07:36:02

标签: laravel laravel-8

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

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.";
}

1 个答案:

答案 0 :(得分:0)

确保您已在 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 希望对您有意义,如有任何疑问,请随时询问。