首页 文章

CI3 /验证规则到配置文件和使用回调

提问于
浏览
0

在将验证规则用于CI3中的配置文件时,我无法确定将回调放在何处 . 这是我的form_validation.php:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 $config = array(
   'blog_post' => array(

      array(
        'field' => 'entry_name', 
        'label' => 'entry_name', 
        'rules' => 'min_length[8]|trim|required|max_length[255]'
        ),

      array(
        'field' => 'entry_body', 
        'label' => 'entry_body', 
        'rules' => 'trim|required|min_length[12]|callback_html_length_without_html'
        ),
    ),
);

function html_length_without_html(){
   if (2 < 1)
    {
        $this->form_validation->set_message('html_length_without_html', 'The field can not be the word');
        return FALSE;
    } else {
        return TRUE;
    }
}

但是,当我运行上面的操作时,我收到以下错误:

Unable to access an error message corresponding 
 to your field name entry_body.(html_length_without_html)

我在哪里放置回调“html_length_without_html()”?

1 回答

  • 1

    您可以extend或在控制器内创建方法 . 我更喜欢使用辅助函数"extend" . 假设您正在使用 $_POST

    application/helpers/form_validation_helper.php 或只是使用MY_form_helper.php进行扩展:

    <?php
    
    if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    if (!function_exists('html_length_without_html')) {
    
    function html_length_without_html() {
        $ci = & get_instance();
        $entry_body = $ci->input->post('entry_body');
        /*Do some check here to define if is TRUE or FALSE*/
        if ($entry_body < 1) {
            $ci->form_validation->set_message('html_length_without_html', 'The field can not be the word');
            return FALSE;
        }
        else {
            return TRUE;
        }
    }
    
    }
    

    $ci->form_validation->set_message('html_length_without_html', 'The field can not be the word'); 没有错,但如果您使用的是lang类,则应将以下行保存到 application/language/english/form_validation_lang.php 中以获得成功的回调响应:

    $lang['html_length_without_html'] = 'The field can not be the word';
    

    在使用之前不要忘记加载助手: $this->load->helper('form_validation_helper');autoload .

相关问题