为Form Validation-Bonfire设置每个规则的自定义错误消息


Set Custom Error messages per rule for Form Validation - Bonfire

我在为每个规则进行表单验证时设置自定义错误消息时遇到问题。

我已经在这里尝试了Bonfire文档

这是我的模块模型的一些代码

class Content_management_system_model extends BF_Model {
    protected $table_name = 'article';
    protected $key = 'id';
    // be updating a portion of the data.
    protected $validation_rules = array(
         array(
            'field' => 'article_alias',
            'label' => 'lang:content_management_system_article_alias',
            'rules' => 'unique[article.article_alias,article.id]',
            'errors' => array(
                'unique' => 'This is my custom error',
            ),
        ),

这里的规则是在插入时从管理员控制器设置的

private function save_content_management_system($type = 'insert', $id = 0) {
        // Validate the data
        $this->form_validation->set_rules($this->content_management_system_model->get_validation_rules());
        if ($this->form_validation->run() === false) {
            return false;
        }

但它总是显示默认消息The value in "Article Alias" is already being used.

根据上述链接中的文档,它应该显示错误This is my custom error

使用回调函数:

$this->form_validation->set_rules('current_pswd', 'Current Password', 'trim|required|callback_alias_exist_check');

public function alias_exist_check($str)
            {
>>Put your code here
            }

我注意到在$validation_rules数组的末尾,它以逗号(,)而不是分号(;)结束。还请删除嵌套数组的逗号,因为在第一个嵌套数组之后没有其他数组。

删除逗号(,)并替换为分号(;)

protected $validation_rules = array(
         array(
            'field' => 'article_alias',
            'label' => 'lang:content_management_system_article_alias',
            'rules' => 'unique[article.article_alias,article.id]',
            'errors' => array(
                'unique' => 'This is my custom error',
            )
        );

此外,您的

if ($this->form_validation->run() **===** false) {
            return false;
        }

有一个3'等于'运算符,这是不必要的。使其仅为2"等于"运算符。

另一个建议:

既然您正在调用content_management_system_model的函数get_validation_rules,为什么不创建一个函数get_validation _rules()并在函数内部创建一个数组,然后返回该数组,而不是将该数组分配给受保护的变量?

function get_validation_rules()
{
    $validation_rules = array(
         'field'  => 'article_alias',
         'label'  => 'lang:content_management_system_article_alias',
         'rules'  => array(
              'unique'   => 'This is my custom error',
          )   
    );
    return $validation_rules;
}

如果您还有其他问题,以及错误是否仍然存在,请告诉我。干杯