[英]How to override the message of the custom validation rule in Laravel?
我正在開發一個 Laravel 應用程序。 我在我的應用程序中所做的是我試圖覆蓋自定義驗證規則消息。
我在請求類中有這樣的驗證規則:
[
'name'=> [ 'required' ],
'age' => [ 'required', new OverAge() ],
];
通常,我們會像這樣覆蓋規則的錯誤消息:
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
但是我怎樣才能對自定義驗證規則類做到這一點呢?
您不能簡單地用請求的自定義消息覆蓋它。 如果你看一下Validator
類:
/**
* Validate an attribute using a custom rule object.
*
* @param string $attribute
* @param mixed $value
* @param \Illuminate\Contracts\Validation\Rule $rule
* @return void
*/
protected function validateUsingCustomRule($attribute, $value, $rule)
{
if (! $rule->passes($attribute, $value)) {
$this->failedRules[$attribute][get_class($rule)] = [];
$this->messages->add($attribute, $this->makeReplacements(
$rule->message(), $attribute, get_class($rule), []
));
}
}
如您所見,它只是將$rule->message()
直接添加到消息包中。
但是,您可以在自定義規則的類中為消息添加參數:
public function __construct(string $message = null)
{
$this->message = $message;
}
然后在您的消息功能中:
public function message()
{
return $this->message ?: 'Default message';
}
最后在你的規則中:
'age' => ['required', new OverAge('Overwritten message')];
使用 Laravel 9,支持覆蓋消息,但您必須為驗證類提供 FQDN。 因此,您的OverAge
自定義消息可能如下所示:
return [
'age.required' => 'An age is required',
'age.App\\Rules\\OverAge' => 'The age must be less than 65',
];
您可能還希望支持消息的占位符,因此65
可以替換為:max-age
類的內容。 發布了許多這樣做的方法,但沒有一個看起來特別干凈。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.