Welcome Guest, Not a member yet? Register   Sign In
CI form_validation callbacks
#1

[eluser]Keloo[/eluser]
Hi,
I'm trying to create a signup form for my website, and I'm trying to check the availability of the username using the callback function provided by CI.

Code:
function signup()
  {
    $this->load->library('form_validation');
    
    // field name, error message, validation rules
    $this->form_validation->set_rules('first_name', 'First Name', 'trim|required');
    $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
    $this->form_validation->set_rules('username', 'Username','callback_username_check');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[32]|md5');
    $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
    $this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');

    
    if($this->form_validation->run() == FALSE)
    {
      $data['main_content'] = 'signup';
      $this->load->view('includes/template',$data);
    }
    
    else
    {    
      $this->load->model('users_model');
      
      if($query = $this->users_model->create_user())
      {
        $data['main_content'] = 'signup_success';
        $this->load->view('includes/template', $data);
      }
      else
      {
        $data['main_content'] = 'signup';
        $this->load->view('includes/template',$data);  
      }
    }
    
  }

  function username_check($str)
  {
    if($str == 'test')
    {
      $this->form_validation->set_message('username_check', 'The %s field can not be the word typed');
      return FALSE;
    }
    
    else
    {
      return TRUE;
    }

So what I'm trying to do is instead of comparing what the user typed with the word "test", to compare it with the 'username' located in the database.
I've spent like 2-3 hours trying to figure out how to do this with CI and the callback function, but I couldn't, and I'm out of ideas now.
Just to mention I'm kinda of a beginner when it comes to php, anyway CI made my life alot easier, but there are still many things that I don't know yet.

I'd be glad if someone could give me a tip on how to do this.
#2

[eluser]Cristian Gilè[/eluser]
model:

Code:
function username_check($username)
{
    $this->db->where('username_field',$username);
    return $this->db->get('table_name')->num_rows();
}

controller:
Code:
function username_check($str)
  {
    $this->load->model('model_name');
    
    if($this->model_name->username_check($str) > 0)
    {

      $this->form_validation->set_message('username_check', '%s username is already registered');
      return FALSE;
    }
    else
    {
      return TRUE;
    }
  }


Cristian Gilè
#3

[eluser]Keloo[/eluser]
Thank you, I've just tried it and it works. Smile




Theme © iAndrew 2016 - Forum software by © MyBB