2012-02-25 57 views
0

我的視圖中含有3個類似的輸入形式:如何在CodeIgniter中爲多個輸入的規則設置唯一的消息?

<input type="text" name="email1" /> 
<input type="text" name="email2" /> 
<input type="text" name="email3" /> 

我添加了一個回調來控制每個文本框不獲取當前會話郵件。

public function check_session_email($email){ 
    if($this->session){ 
     if ($this->session->userdata('email') != $email){ 
      return TRUE; 
     }else{ 
      $this->form_validation->set_message('check_session_email', 'You can't include your own email address.'); 
      return FALSE; 
     } 
    } 
} 

如果我用了本屆會議的電子郵件,該錯誤消息顯示兩次(同樣的事情有三個)。

enter image description here

當然,這聽起來合乎邏輯......但不是很人性化。所以我的問題是:如何只包含一條規則的錯誤消息?

+0

如果你能得到CI把消息在數組中,你可以使用['array_unique()'] (http://php.net/manual/en/function.array-unique.php)。 – Bojangles 2012-02-25 20:25:06

回答

1

你最好的選擇是在表單驗證庫之外驗證這一點。

控制器的方法:

// general validation rules 

if($this->input->post('email1') == $this->session->userdata('email') || $this->input->post('email2') == $this->session->userdata('email') || $this->input->post('email3') == $this->session->userdata('email')) 
{ 
    $data['own_mail_error'] = true; 
} 

if ($this->form_validation->run() == FALSE || isset($data['own_mail_error'])) 
{ 
    $this->load->view('myform', $data); 
} 
else 
{ 
    $this->load->view('formsuccess'); 
} 

而且你的觀點:

<?php echo validation_errors(); ?> 
<?php if(isset($own_mail_error)): ?> 
<p>You can't include your own email address.</p> 
<?php endif; ?> 
+0

謝謝,這是有道理的。我用'if(in_array($ this-> session-> userdata('email'),$ this-> input-> post()))'替換了第一行以縮短內容。 – Dacobah 2012-02-26 15:33:55

0
public function check_session_email($email) 
    { 
     if($this->session) 
     { 
      if ($this->session->userdata('email') != $email) 
      { 
       return TRUE; 
      } 
     } 
     else 
     { 
      if($this->form_validation->_field_data['email1']['error']=='' && $this->form_validation->_field_data['email2']['error']=='' && $this->form_validation->_field_data['email3']['error']=='') 
      { 
       $this->form_validation->set_message('check_session_email', 'You can\'t include your own email address.'); 
      } 
      return FALSE; 
     } 
    } 
相關問題