2012-07-30 99 views
2

假設我在CodeIgniter中有一個登錄表單 - 我可以爲各個輸入設置驗證規則,但是有沒有辦法引發模型/控制器級錯誤和消息?在CodeIgniter中設置通用表單驗證錯誤

具體來說,如果下面的方法沒有返回TRUE,我希望我的表單重新顯示消息「電子郵件地址或密碼不正確」。目前,該控制器剛剛重新加載視圖和SET_VALUE

public function authorize_user() 
{ 
    $this->db->where('email', $this->input->post('email')); 
    $this->db->where('password', $this->input->post('password')); 

    $q = $this->db->get('users'); 

    if($q->num_rows() == 1){ 
     return true; 
    } 
} 

也許我該得太多,我應該只是附上錯誤信息的電子郵件輸入()秒?

回答

3

您可以使用回調函數來完成此操作。步驟如下:
1.您的authorize_user()函數必須在您設置規則的控制器中。我添加的參數爲回調函數

$this->form_validation->set_rules('email', 'email', 'callback_authorize_user['.$this->input->post("password").']'); 

注:
2.您可以通過添加類似的代碼做一個「回調」的規則。這些函數自動接收由set_rules()的第一個參數確定的參數。在這種情況下,自動傳遞給回調函數的參數是電子郵件。此外,我將密碼作爲第二個參數傳遞。

3.添加相應的參數,以你的函數:http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks

希望它能幫助:在

public function authorize_user($email,$password) 
{ 
    //As I said before, the email is passed automatically cause you set the rule over the email field. 
    $this->db->where('email', $email); 
    $this->db->where('password', $password); 

    $q = $this->db->get('users'); 

    if($q->num_rows() == 1){ 
     return true; 
    } 
} 

更多信息!

+0

啊啊,太好了,謝謝。我讀過關於向回調中添加第二個參數的問題,但沒有想到以這種方式使用它。 – 2012-07-31 04:31:52