简体   繁体   中英

Validating User and Not Validating User

I'm attempting to validate an input field for the username. I created a callback function to report back if the user input already exists as a name in the database or not but every time it reports back that it does exist. Even when there's nothing in the database. The call to the function save is from a jquery ajax request.

public function save()
{
    $output_status = 'Error';
    $output_title = 'Not processed';
    $output_message = 'The request was unprocessed!';

    $this->form_validation->set_rules('username', 'User Name', 'required|trim|xss_clean|callback_username_check');

    if ($this->form_validation->run())
    {
        $user_saved = $this->users_model->save_user($this->input->post('username'), $this->input->post('user_directory_name'), $this->input->post('user_status'));
        if ($user_saved)
        {
            $output_status = 'Success';
            $output_title = 'User Created';
            $output_message = 'User was successfully created!';
        }
        else
        {
            $output_title = 'User Not Created';
            $output_message = 'User was not successfully created!';
        }
    }
    else
    {
        $output_title = 'Form Not Validated';
        $output_message = validation_errors();
    }
    echo json_encode(array('status' => $output_status, 'title' => $output_title, 'message' => $output_message));  
}

public function username_check($title_name)
{
    $username_exists = $this->users_model->get_user(array('username' =>$username));
    if (is_null($username_exists))
    {
        $this->form_validation->set_message('username_check', 'The username already exists!');
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}  

It's probably because your callback function is using a variable that is not defined. You should either change $username to $title_name or visa versa.

public function username_check($username)
{
  $username_exists = $this->users_model->get_user(array('username' =>$username));
  if (is_null($username_exists))
  {
    $this->form_validation->set_message('username_check', 'The username already exists!');
    return FALSE;
  }
  else
  {
    return TRUE;
  }
}  

你可以从规则:$ this-> form_validation-> set_rules('username','Username','required | is_unique [users.username]');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM