Internationalization Kohana 3.2中的自定义i18n错误消息

Internationalization Kohana 3.2中的自定义i18n错误消息,internationalization,kohana,kohana-3.2,Internationalization,Kohana,Kohana 3.2,我了解在Kohana 3.2中创建自定义错误消息的方法: 我的问题是重复太多,因为我需要一个单独的文件用于用户模型、Post模型等 在大多数情况下,是否有办法使用我自己的错误消息?我想在i18n中使用它们。您可以在application/messages/validate.php中为每个验证规则设置默认错误消息: <?php return array( 'not_empty' => 'Field is empty', 'Custom_Class::custom_met

我了解在Kohana 3.2中创建自定义错误消息的方法:

我的问题是重复太多,因为我需要一个单独的文件用于用户模型、Post模型等


在大多数情况下,是否有办法使用我自己的错误消息?我想在i18n中使用它们。

您可以在application/messages/validate.php中为每个验证规则设置默认错误消息:

<?php
return array(
    'not_empty' => 'Field is empty',
    'Custom_Class::custom_method' => 'Some error'
);
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;
}
您还可以通过在application/classes/Validate.php中扩展默认验证类来更改其行为:

<?php
return array(
    'not_empty' => 'Field is empty',
    'Custom_Class::custom_method' => 'Some error'
);
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!',

当然,请根据您的自定义验证规则调整上述内容。

谢谢,但我想在ORM中使用自定义错误消息。此外,我认为您的解决方案存在一些错误:例如,您的验证类可能必须扩展Kohana_验证而不是Kohana_验证。“return$messages;”的位置也很有趣…
消息国际化的方式是这样的
--:不要在消息文件中使用“\”,因为这些文件可能会被缓存并且无法正常工作。