Kohana 3.2:自定义验证规则的自定义错误消息?

kri*_*che 1 kohana kohana-3

我在我的模型中使用自定义方法来验证规则(使用Kohana 3.2).我遵循文档中列出的格式.

// Calls A_Class::a_method($value);
array(array('A_Class', 'a_method')),
Run Code Online (Sandbox Code Playgroud)

但是,如果规则失败,我似乎无法弄清楚如何添加自定义错误消息.

有帮助吗?

Fad*_*ife 7

对于这个例子,我们假设一个模态"用户"并验证字段"username"

/application/classes/model/user.php

class Model_User extends ORM
{
    public function rules()
    {
        return array(
            'username' => array(
                array('not_empty'),
                array('A_Class::a_method', array(':value')),
            )
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

一类

public static function a_method($value)
{
    // Validate and return TRUE or FALSE
}
Run Code Online (Sandbox Code Playgroud)

/application/messages/forms/user.php
添加了一个表单文件夹,以便我们可以选择要加载错误的邮件文件.消息文件与模型名称(用户)匹配

return array(
    'username' => array(
        'not_empty'         => 'Custom error message for not_empty method',
        'A_Class::a_method' => 'Custom error message for you own validation rule...'
    ),
);
Run Code Online (Sandbox Code Playgroud)

现在在您的控制器中验证并显示错误消息

class Controller_User extends Controller
{
    // User model instance
    $model = ORM::factory('user');

    // Set some data to the model
    $model->username - 'bob';

    // Try to validate and save
    try
    {
        $model->save()
    }
    catch (ORM_Validation_Exception $e)
    {
        // Loads messages from forms/user.php
        $errors = $e->errors('forms');

        // See the custom error messages
        echo Debug::vars($errors);
    )
)
Run Code Online (Sandbox Code Playgroud)