验证用户和不验证用户

时间:2012-11-27 00:29:07

标签: php codeigniter

我正在尝试验证用户名的输入字段。我创建了一个回调函数来报告用户输入是否已作为数据库中的名称存在,但每次报告它确实存在时。即使数据库中没有任何内容。对函数save的调用来自jquery ajax请求。

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

2 个答案:

答案 0 :(得分:1)

这可能是因为你的回调函数正在使用未定义的变量。 您应该将$ username更改为$ title_name,反之亦然。

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

答案 1 :(得分:1)

您可以通过规则执行此操作:  $ this-> form_validation-> set_rules('username','Username','required | is_unique [users.username]');