CodeIgniter - 无法访问与您的字段名称对应的错误消息

时间:2017-08-24 11:44:01

标签: php codeigniter

我正在创建一个库来添加新用户。

class Register
    {
        private $CI;
        public function add_new_user()
        {
            $CI =& get_instance();
            $CI->form_validation->set_rules('email', 'Email', 'required|callback_is_email_exist');
            if ($CI->form_validation->run() == TRUE)
            {
                $email = $_POST['email'];
                $insert_data = array('email' => $email);
                $CI->new_data->add_user($insert_data);
            }
        }
        private function is_email_exist($email)
        {
            $CI =& get_instance();
            $email_result = '';
            $query = $CI->check->find_email($email);
            foreach ($query->result_array() as $row)
            {
                $email_result = $row['email'];
            }
            if ($email_result == $email)
            {
                $CI->form_validation->set_message('is_email_exist', 'Such email already exist!');
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
    }

我将 form_validation check,new_data 模型添加到自动加载中。当我提交表单而不是错误时(如果它应该在那里)我得到无法访问与您的字段名称Username相对应的错误消息。(is_username_exist)。我该怎么做才能得到正确的错误?

2 个答案:

答案 0 :(得分:0)

Codeigniter表单验证是针对控制器的,所以当提交表单时,它会去那里

https://www.codeigniter.com/user_guide/libraries/form_validation.html#the-controller

控制器方式

<?php

class Register extends CI_Controller
{

    public function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->model('some_model');
    }

    public function index() {
        $this->form_validation->set_rules('email', 'Email', 'required|callback_is_email_exist');

        if ($this->form_validation->run()) {

            $insert_data = array(
                'email' => $this->input->post('email')
            );

            $this->some_model->new_data->add_user($insert_data);
        }

        $data['title'] = 'Welcome To Codeigniter';

        $this->load->view('header', $data);
        $this->load->view('someview', $data);
        $this->load->view('footer');

    }

    // Check user email
    public function is_email_exist() {
        // Single input check
        $this->db->where('email', $this->input->post('email'));
        $query = $this->db->get('user');

        // If user email greater than 0
        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            $this->form_validation->set_message('is_email_exist', 'Such email already exist!');
            return FALSE;
        }

    }


}

答案 1 :(得分:0)

将'is_email_exist'替换为__FUNCTION__为我工作,

https://stackoverflow.com/a/38950446/2420302