2011-08-10 72 views
2

我有一個適當的表單驗證規則有一些複選框的形式:笨 - 複選框表單驗證

$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required'); 

如果沒有我的複選框被提交時檢查,我的代碼一直無法驗證 - >運行的變量不存在:

if ($this->form_validation->run()): 

如果我環繞我的驗證規則與風險價值進行檢查,確認從未通過,因爲沒有其他形式的驗證規則:

if(isset($_POST['groupcheck'])): 
    $this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required'); 
endif; 

如何管理var可能不存在的複選框驗證規則,它將是唯一的表單變量?

問候,本。

+0

什麼是'required'呢?如果您至少需要一個複選框,那麼您的第一個代碼就可以。如果不是必需的,只需將其刪除... –

+0

@ldiqual - 感謝指針。我刪除了「必需的」,但在沒有選中複選框時它仍然無法運行: 'code' $ this-> form_validation-> set_rules('groupcheck []','groupcheck',''); \t \t \t \t if($ this-> form_validation-> run()): echo「test」; – Ben

+0

我能想到的唯一選擇是將一個隱藏的表單域放入,並對其進行驗證。這樣一個驗證規則將始終通過。看起來像一個黑客,但。 – Ben

回答

2

不要笨使用isset()函數作爲笨提供更好的類來檢查,如果你正在檢查的POST變量是存在與否,例如嘗試使用此代碼,而不是你的代碼:

if($this->input->post('groupcheck')): 
    $this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required'); 
endif; 

關於Guidline如何在CodeIgniter中使用POST和GET變量,請查看這裏的用戶指南:http://codeigniter.com/user_guide/libraries/input.html

+0

感謝指針,但我不是確定如果var沒有設置,這將如何讓我的表單驗證運行。它仍然會失敗: 'code' if($ this-> form_validation-> run()): 'code' – Ben

+3

它失敗了,因爲您將groupcheck設置爲required,並且使得groupcheck複選框至少被檢查一次應該檢查,因爲它是必需的。 –

0

我有同樣的問題。 如果您的複選框未被選中,那麼它將永遠不會被髮布。刪除set_rules您的複選框後您的其他形式的驗證規則,你可以試試:

if ($this->form_validation->run() == TRUE){ // form validation passes 

     $my_checkbox_ticked = ($this->input->post('my_checkbox')) ? yes : no; 
0

您可以$this->form_validation->run()比較後validation_errors()如果是FALSE那麼沒有什麼是驗證,所以你可以做某件事,或者顯示警告

if ($this->form_validation->run() == FALSE) { 
    if (validation_errors()) { 
     echo validation_errors(); 
    } else { 
     echo 'empty'; 
    } 
} 
0

您還需要設置按鈕提交

$this->form_validation->set_rules('terminos_form', 'TERM', 'required'); 
    $this->form_validation->set_rules('terminosbox', 'TERM BOX', 'callback__acept_term'); 

回調

function _acept_term($str){ 
     if ($str === '1'){ 
      return TRUE; 
     } 
      $this->form_validation->set_message('_acept_term', 'Agree to the terms'); 
      return FALSE; 
} 

HTML

<input type="checkbox" name="terminosbox" value="1"/> 
<button type="submit" name="terminos_form" value="1">NEXT</buttom>