Kohana 3.2:自定义验证规则的自定义错误消息? [英] Kohana 3.2: Custom error message for a custom validation rule?

查看:102
本文介绍了Kohana 3.2:自定义验证规则的自定义错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a custom method for a validation rule in my model (using Kohana 3.2). I am following the format listed on the documentation.

// Calls A_Class::a_method($value);
array(array('A_Class', 'a_method')),

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

But I can't seem to figure out how to add a custom error message if the rule fails.

有帮助吗?

推荐答案

在此示例中,我们假设使用模式用户"并验证字段用户名"

For this example we will assume a modal "user" and validating the field "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')),
            )
        );
    }
}

A_Class

public static function a_method($value)
{
    // Validate and return TRUE or FALSE
}

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

/application/messages/forms/user.php
Added a forms folder so show we can select message file to load with errors. Message file matches model name (user)

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...'
    ),
);

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

Now in your controller to validate and display the error messages

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);
    )
)

这篇关于Kohana 3.2:自定义验证规则的自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆