使用自定义规则的模型方法进行表单验证的错误消息

时间:2015-11-11 19:59:05

标签: php codeigniter codeigniter-3

我需要显示自定义验证规则的错误消息,但我无法执行此操作。

这是验证规则:

    $config = array(
             ....,
            array(
                    'field' => 'general_sales_subaccount',
                    'label' => 'General Sales Subaccount',
                    'rules' => array(
                            'required',
                            'numeric',
                            array(
                                    $this->subaccounts_model,
                                    'is_valid'
                            )
                    ),
            )
    );

    $this->form_validation->set_rules($config);

现在这是引用的模型方法:

    public function is_valid($subaccount)
    {
        $subaccount_num_digits = $this->preferences->get('subaccount_num_digits');

        if (strlen($subaccount) != $subaccount_num_digits ) {
            $this->form_validation->set_message('is_valid', "The number of digits in %s doesn't match the length set to " . $subaccount_num_digits);
            return false;
        }       

        return true;
    }

该规则似乎有效,但它显示以下错误消息:

无法访问与您的字段名称相对应的错误消息(匿名函数)。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您无法收到错误消息,因为您没有设置功能名称。您可以更改您的规则功能,如下所示:

$config = array(
         ....,
        array(
                'field' => 'general_sales_subaccount',
                'label' => 'General Sales Subaccount',
                'rules' => array(
                        'required',
                        'numeric',
                        array( //you may get all in another array
                          'is_valid', // and tell codeigniter your functions name
                          array(
                                $this->subaccounts_model,
                                'is_valid'
                        )
                    )
                ),
        )
);

$this->form_validation->set_rules($config);
相关问题