2016-07-29 127 views
0

我是codeigniter的新手。我現在創建了一個登錄頁面,如果用戶輸入錯誤的憑據,我想顯示一條錯誤消息,指出登錄詳細信息是錯誤的或無效登錄。我不知道我做錯了,但是當我輸入錯誤的憑據的頁面是沒有任何錯誤信息表單驗證set_message在codeigniter中沒有顯示任何錯誤

function login_user() { 
    // Create an instance of the user model 
    $this->load->model('user_m'); 

    // Grab the email and password from the form POST 
    $username= $this->input->post('username'); 
    $pass = $this->input->post('password'); 
    $this->form_validation->set_rules('username', 'Username', 'required|trim'); 

    $this->form_validation->set_rules('password', 'Password', 'required|trim'); 
    $this->load->helper('security'); 
    if($this->form_validation->run() == FALSE){ 
     $this->load->view('login'); 
    } 

    if($username && $pass && $this->user_m->validate_user($username,$pass)) { 
     // If the user is valid, redirect to the main view 
     redirect('/dashboard'); 
    } else { 
     // Otherwise show the login screen with an error message. 
     $this->form_validation->set_message('login_user','Wrong email, password combination.'); 
     $this->load->view('login'); 
    } 

}

在我看來

我使用以下行來顯示錯誤

<?php echo validation_errors(); ?> 
刷新

「用戶名和密碼字段是必需的」錯誤工作正常,但無效登錄不起作用

回答

2

我認爲問題是ELSE代碼片段的最後一節。所以你寫了這樣的東西。

簡短的定義

$this->form_validation->set_message() 

只有當驗證規則可能會失敗的工作。所以我假設你輸入了usernamepassword錯誤,但你填寫了required邏輯。所以form_validation通過這個測試用例。 所以更改$this->form_validation->set_message()到以下幾點:

更換

if($username && $pass && $this->user_m->validate_user($username,$pass)) { 
    // If the user is valid, redirect to the main view 
    redirect('/dashboard'); 
} else { 
    // Otherwise show the login screen with an error message. 
    $this->form_validation->set_message('login_user','Wrong email, password combination.'); 
    $this->load->view('login'); 
} 

if($username && $pass && $this->user_m->validate_user($username,$pass)) { 

     // If the user is valid, redirect to the main view 
     redirect('/dashboard'); 

    } else { 

     // Otherwise show the login screen with an error message. 

     $this->session->set_flashdata('authError', 'Username or Password Invalid !!'); 
     $this->load->view('login'); 
    } 

而且在VIEW頁寫這樣的事情:

更換

<?php echo validation_errors(); ?> 

<?php if($this->session->flashdata('authError')) 
{ 
    echo $this->session->flashdata('authError'); 
}?>