首页 文章

创建自定义codeigniter验证规则

提问于
浏览
22

我的登录表单中有一个函数,用于检查电子邮件和密码是否与数据库中的值匹配,如果是,则将用户登录到系统中 .

如果此函数返回false,我想显示验证错误 .

我的问题是我不确定如何创建它 . 该消息与密码和电子邮件字段有关,因此我不希望每个输入字段的规则只显示一条消息 .

我已经尝试使用flashdata来实现这一点但它只在页面刷新时才有效 .

如何仅为函数 $this->members_model->validate_member() 创建新的验证规则?

$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        $this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', '"Password"', 'trim|required');

        if ($this->form_validation->run() == FALSE)
        {
            $viewdata['main_content'] = 'members/login';
            $this->load->view('includes/template', $viewdata);
        }
        else
        {       
                if($this->members_model->validate_member())
                {

2 回答

  • 7

    您在规则中使用 callback_ ,参见callbacks,例如 .

    $this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member');
    

    并在控制器中添加该方法 . 此方法需要返回TRUE或FALSE

    function validate_member($str)
    {
       $field_value = $str; //this is redundant, but it's to show you how
       //the content of the fields gets automatically passed to the method
    
       if($this->members_model->validate_member($field_value))
       {
         return TRUE;
       }
       else
       {
         return FALSE;
       }
    }
    

    然后,您需要在验证失败时创建相应的错误

    $this->form_validation->set_message('validate_member','Member is not valid!');
    
  • 42

    实现这一目标的最佳方法是扩展CodeIgniter的表单验证库 . 假设我们要为数据库表 users 的字段 access_code 创建名为 access_code_unique 的自定义验证器 .

    您所要做的就是在 application/libraries 目录中创建一个名为 MY_Form_validation.php 的类文件 . 该方法应始终返回 TRUEFALSE

    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class MY_Form_validation extends CI_Form_validation {
        protected $CI;
    
        public function __construct() {
            parent::__construct();
                // reference to the CodeIgniter super object
            $this->CI =& get_instance();
        }
    
        public function access_code_unique($access_code, $table_name) {
            $this->CI->form_validation->set_message('access_code_unique', $this->CI->lang->line('access_code_invalid'));
    
            $where = array (
                'access_code' => $access_code
            );
    
            $query = $this->CI->db->limit(1)->get_where($table_name, $where);
            return $query->num_rows() === 0;
        }
    }
    

    现在,您可以轻松添加新创建的规则

    $this->form_validation->set_rules('access_code', $this->lang->line('access_code'), 'trim|xss_clean|access_code_unique[users]');
    

相关问题