0

因此,我尝试在 CodeIgniter (v2.1.4) 中使用带有 Form_validation 库的回调函数来检查数据库中是否存在具有给定用户名或电子邮件的用户,然后再创建新用户。

login.php(控制器)

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;
    }
}

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

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

4

2 回答 2

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

于 2013-07-26T21:11:21.530 回答
0

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

于 2013-07-27T07:08:18.193 回答