使用CodeIgniter表单验证回调函数的HTTP 500错误

时间:2013-07-26 20:53:29

标签: php codeigniter callback

所以我正在尝试使用CodeIgniter(v2.1.4)中的Form_validation库的回调函数来检查在创建新用户之前数据库中是否存在具有给定用户名或电子邮件的用户。

login.php(Controller)

function create_member()
{
    $this->load->library('form_validation');
    $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|callback_value_check[USERNAME]');

    if($this->form_validation->run() != FALSE)
    {
        // Validation passed; create the new user.
        $this->load->model("members_model");
        if($query = $this->members_model->create_member())
        {
            // Load the success page view.
        }
        else
        {
            // Reload the signup page view.
        }
    }
    else
    {
        // Reload the signup page view.
    }
}

function _value_check($value, $column)
{   
    $this->load->model("members_model");
    if($this->members_model->check_exist_value($column, $value))
    {
        $this->form_validation->set_message('value_check', '%s is already taken.');
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

members_model.php(模特)

function check_exist_value($column, $value)
{
    $this->db->where($column, $value);  
    $result = $this->db->get('MEMBERS');

    if($result->num_rows() > 0)
    {
        // A user with that unique value already exists in the database.
        return TRUE;
    }
    else
    {
        // There is no user with that unique value in the database.
        return FALSE;
    }
}

如上面的代码所示,我目前只测试现有的用户名。标准验证消息正确显示(即必需,min_length等)。但是,如果我输入一个我知道已存在于数据库中的值(意味着自定义回调验证函数应该失败),我会收到HTTP 500错误(Chrome的默认“服务器错误”页面)。

有没有人知道为什么我收到HTTP 500错误而不是看到我的自定义错误消息?

2 个答案:

答案 0 :(得分:0)

我不知道为什么你使用回调电子邮件/用户名唯一检查当codeigniter已在form_validation类中提供此功能时,只需在验证规则中添加唯一规则检查,其中包含具有以下内容的表名和列电子邮件/用户名也提供表格列

$this->form_validation->set_rules('username', 'Username', 
'trim|required|min_length[4]|unique[tablename.column_email_username,tablename.id]');

$this->form_validation->set_rules('username', 'Username', 
'trim|required|min_length[4]|is_unique[tablename.column_email_username]');

希望 unique [tablename.column_email_username,tablename.id] 完成工作,您将不会遇到服务器错误

或者试试is_unique

答案 1 :(得分:0)

Ahaha,原来在验证失败时重新加载视图的部分中有一个类型。只需要休息一下,重新阅读我必须发现的内容!