【问题标题】:Kohana 3.2: Custom error message for a custom validation rule?Kohana 3.2:自定义验证规则的自定义错误消息?
【发布时间】:2012-03-24 10:05:57
【问题描述】:

我正在为我的模型中的验证规则使用自定义方法(使用 Kohana 3.2)。我遵循the documentation 中列出的格式。

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

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

有什么帮助吗?

【问题讨论】:

    标签: kohana kohana-3


    【解决方案1】:

    对于这个例子,我们将假设一个模态“用户”并验证字段“用户名”

    /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
    添加了一个表单文件夹,以便显示我们可以选择消息文件以加载错误。消息文件匹配模型名称(用户)

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 2016-10-21
      • 1970-01-01
      • 2021-12-09
      • 2011-04-29
      相关资源
      最近更新 更多