2015-05-04 185 views
3

我想創建此擴展驗證。Laravel擴展驗證自定義消息

Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) { 
    // I guess I should be setting the error message for this here.(Its dynamic) 
    // We can return true or false here depending upon our need. 
} 

我會用這個規則是這樣

'my_field' => 'required|my_custom_validation_rule'

我想用一些動態消息的錯誤「my_custom_validation_rule

我無法找到的東西有關它的文檔。無論如何去做?

+2

再看看:http://laravel.com/docs/5.0/validation#custom-error-messages – lukasgeiter

+0

我想在Validator :: extend中提供消息('my_custom_validation_rule',s closure本身,有可能嗎? –

回答

13

extend方法允許通過將消息作爲第三個參數:

Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) { 
    // ... 
}, 'my custom validation rule message'); 

在默認情況下,只能使用動態變量,這是:attribute。如果你想添加更多的使用Validator::replacer()

Validator::replacer('my_custom_validation_rule', function($message, $attribute, $rule, $parameters){ 
    return str_replace(':foo', $parameters[0], $message); 
}); 
+0

有沒有什麼辦法可以讓這個消息變成動態的呢?我的意思是我的消息根據$ attribute,$ value,$參數 - 我可以像第二個參數一樣使用閉包嗎? –

+0

查看已更新的答案 – lukasgeiter

0

您也可以定義爲待驗證的翻譯文件自定義的驗證規則的消息。

/resources/lang/en/validation.php

.... 
'unique'     => 'The :attribute has already been taken.', 
'uploaded'     => 'The :attribute failed to upload.', 
'url'      => 'The :attribute format is invalid.', 
//place your translation here 
'my_custom_validation_rule' => 'The :attribute value fails custom validation.'