我理解的Kohana 3.2創建自定義錯誤消息的方式:Kohana 3.2: Custom error message for a custom validation rule?定製國際化的錯誤信息3.2
我與它的問題是過多贅述,因爲我需要一個單獨的文件爲用戶模型,郵政型號等
有沒有什麼辦法使用我自己的錯誤消息,通常大多數情況下?我想用i18n來使用它們。
我理解的Kohana 3.2創建自定義錯誤消息的方式:Kohana 3.2: Custom error message for a custom validation rule?定製國際化的錯誤信息3.2
我與它的問題是過多贅述,因爲我需要一個單獨的文件爲用戶模型,郵政型號等
有沒有什麼辦法使用我自己的錯誤消息,通常大多數情況下?我想用i18n來使用它們。
您可以設置一個默認的錯誤消息,在應用程序/消息/ validate.php每個驗證規則:
<?php
return array(
'not_empty' => 'Field is empty',
'Custom_Class::custom_method' => 'Some error'
);
這將返回消息「字段爲空」爲下面的例子:
$post_values = array('title'=>'');
$validation = Validate::factory($post_values)
->rules('title', array(
'not_empty'=>NULL));
if($validation->check()){
// save validated values
$post = ORM::factory('post');
$post->values($validation);
$post->save();
}
else{
$errors = $validation->errors(true);
}
您還可以通過將其擴展到application/classes/validate.php中來更改默認驗證類的行爲:
class Validate extends Kohana_Validate
{
public function errors($file = NULL, $translate = TRUE)
{
// default behavior
if($file){
return parent::errors($file, $translate);
}
// Custom behaviour
// Create a new message list
$messages = array();
foreach ($this->_errors as $field => $set)
{
// search somewhere for your message
list($error, $params) = $set;
$message = Kohana::message($file, "{$field}.{$error}");
}
$messages[$field] = $message;
}
return $messages;
}
消息國際化的方式如下:在消息文件中用翻譯調用替換實際的英文文本,如下所示。
return array
(
'code' => array(
'not_empty' => __('code.not_empty'),
'not_found' => __('code.not_found'),
),
);
翻譯隨後作爲一般的文件處理,通過條目的i18n文件夾,例如:
'code.not_empty' => 'Please enter your invitation code!',
當然,調整上述對您的自定義的驗證規則。
'消息國際化的方式就像這樣 - 「[Kohana 3.2文檔](http://kohanaframework.org/3.2/guide/kohana/files/messages): *不要在消息文件中使用__(),因爲這些文件可能被緩存,並且無法正常工作。* – 2012-10-03 19:55:53
謝謝,但我想用自定義錯誤消息與ORM。 – Subi 2012-04-24 19:17:09
此外,我認爲你的解決方案有一些錯誤:例如,也許你的Validate類必須擴展Kohana_Validation而不是Kohana_Validate。 「返回$消息;」位置也很有趣...... – Subi 2012-04-24 19:46:17