簡體   English   中英

為 laravel 中的自定義驗證規則自定義驗證錯誤消息

[英]Customizing validation error message for a custom validation rule in laravel

在我的 controller 中,我正在嘗試為自定義驗證規則自定義錯誤消息。 問題是自定義規則沒有名稱,因此我在自定義此規則的錯誤消息時遇到了一些困難。

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 class 中定義了message()方法以返回驗證消息,例如

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

或者可以將自定義驗證消息添加到resources/lang/en/validation.php文件,索引為“custom_rule”,例如

'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希望這對您有意義,請隨時詢問是否仍有任何疑問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM