2012-11-27 138 views
0

我正在嘗試驗證用戶名的輸入字段。我創建了一個回調函數來回報用戶輸入是否已經作爲名稱存在於數據庫中,但是每次都會報告它確實存在。即使數據庫中沒有任何內容。對函數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; 
    } 
} 

回答

1

你能做到這一點從規則: $這個 - > form_validation-> set_rules( '用戶名', '用戶名', '需要| is_unique [users.username]');

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