2011-11-18 73 views
18

我在我的登錄表單中有一個函數,用於檢查電子郵件和密碼是否與數據庫中的值匹配,如果是,則會將用戶登錄到系統中。創建一個自定義的代碼驗證規則

如果此函數返回false,我想顯示驗證錯誤。

我的問題是,我不確定如何去創建這個。該消息與密碼和電子郵件字段相關,因此我不希望每個輸入字段的規則只顯示一條消息。

我已經嘗試使用flashdata來實現這一點,但它只適用於頁面已被刷新。

如何爲功能$this->members_model->validate_member()創建新的驗證規則?

$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); 
     $this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email'); 
     $this->form_validation->set_rules('password', '"Password"', 'trim|required'); 

     if ($this->form_validation->run() == FALSE) 
     { 
      $viewdata['main_content'] = 'members/login'; 
      $this->load->view('includes/template', $viewdata); 
     } 
     else 
     {  
       if($this->members_model->validate_member()) 
       { 

回答

38

你用你的規則callback_,看到callbacks,爲前。

$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member'); 

並在控制器中添加該方法。此方法需要返回TRUE或FALSE

function validate_member($str) 
{ 
    $field_value = $str; //this is redundant, but it's to show you how 
    //the content of the fields gets automatically passed to the method 

    if($this->members_model->validate_member($field_value)) 
    { 
    return TRUE; 
    } 
    else 
    { 
    return FALSE; 
    } 
} 

然後,您需要在情況下創建一個相應的錯誤驗證失敗來實現這一目標是擴大CodeIgniter的表單驗證庫

$this->form_validation->set_message('validate_member','Member is not valid!'); 
+2

名稱「_validate_member」會更好.. – Ivan

+0

@Ivan這是沒有必要的,但可以添加可讀性,謝謝 –

+6

可能不是必需的,但是一個前導下劃線將阻止通過「/ controller_name/validate_member/blah」訪問該方法...並且使用雙下劃線是完全可以接受的IMO「callback__validate_member」;) –

5

一個最好的辦法。假設我們要爲數據庫表users的字段access_code創建一個名爲access_code_unique的自定義驗證程序。

您所要做的就是在application/libraries目錄中創建一個名爲MY_Form_validation.php的Class文件。該方法應該總是返回TRUE OR FALSE

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

class MY_Form_validation extends CI_Form_validation { 
    protected $CI; 

    public function __construct() { 
     parent::__construct(); 
      // reference to the CodeIgniter super object 
     $this->CI =& get_instance(); 
    } 

    public function access_code_unique($access_code, $table_name) { 
     $this->CI->form_validation->set_message('access_code_unique', $this->CI->lang->line('access_code_invalid')); 

     $where = array (
      'access_code' => $access_code 
     ); 

     $query = $this->CI->db->limit(1)->get_where($table_name, $where); 
     return $query->num_rows() === 0; 
    } 
} 

現在,您可以輕鬆地添加新創建的規則

$this->form_validation->set_rules('access_code', $this->lang->line('access_code'), 'trim|xss_clean|access_code_unique[users]');