0
votes

So I'm trying to use a callback function with the Form_validation library in CodeIgniter (v2.1.4) to check whether a user with a given username or email exists in the database before creating a new user.

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 (Model)

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

As seen in the code above, I'm only currently testing for an existing username. The standard validation messages appear correctly (i.e. required, min_length, etc). However, if I enter a value that I know to be already in the database (meaning the custom callback validation function should fail) I instead get an HTTP 500 error (Chrome's default 'Server error' page).

Does anyone have any insight as to why I'm getting an HTTP 500 error instead of seeing my custom error message?

2

2 Answers

0
votes

I don't know why you are using you callback for the email/username unique check when codeigniter already provides this functionality in the form_validation class just add the unique rule check in the validation rules with the table name and column that has the emails/usernames also provide the table is column

$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]');

Hope unique[tablename.column_email_username,tablename.id] does the job and you will not face the server error

OR try this for is_unique

0
votes

Ahaha, turned out there was a type in the section reloading the view when the validation failed. Just needed to take a break and re-read through what I had to spot it!