我理解的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