首页 文章

自定义表单验证类

提问于
浏览
0

我创建了从CI_Form_validation类扩展的My_Form_validation类 .

我创建了一个自定义方法来验证带有空格的字符串,并正常工作 . 但是,现在我需要验证数据库中是否存在id .

所以我在My_Form_validation中创建了一个方法来检查它,但不起作用,验证总是返回false:

My_Form_validation

class My_Form_validation extends CI_Form_validation {

    public function get_error_array(){
        return $this->_error_array;
    }

    public function alpha_space($value){
        $str = str_replace(" ", "", $value);
        return ctype_alpha($str);
    }

    public function entity_exist($id){
        return true;
    }
}

Validation rule

'entity_report' => array(
    array(
        'field' => 'id',
        'label' => 'id',
        'rules' => 'trim|required|is_natural_no_zero|entity_exist'
    )
)

为什么Codeigniter没有从验证类中捕获验证器?我不想在控制器中使用验证器方法 .

有任何想法吗 ?

2 回答

  • 0

    我认为你没有制作 CI 实例的问题

    function __construct() {
    parent::__construct();
     // reference to the CodeIgniter super object
    $this->CI =& get_instance();
    }
    

    并设置验证规则,如

    $this->CI->form_validation->set_message('email_check', 'The %s is not valid.');
    
  • 0
    You can Use like this
    
        create form_validation.php file in config folder.
    
    
         $config = array(
        'entity_report' => array(
            array(
                'field' => 'id',
                'label' => 'ID',
                'rules' => 'required|min_length[2]'
            )
        )
    );
    
        insert this line in autoload.php
        $autoload['config'] = array('form_validation');
    
        if ($this->form_validation->run('entity_report') == FALSE) {
           Your code here.
        } else { 
         your code here. 
        }
    

相关问题