2013-03-12 85 views
4

我有兩個數字字段來收集用戶的數據。需要使用codeigniter表單驗證類來驗證它。Codeigniter:驗證兩個字段

條件:

  1. 第一場可以是零
  2. 第二字段不能爲零
  3. 第一字段不應該等於第二場
  4. 第二場應該比第一場
  5. 更大

目前我用

$ this-> form_validation-> set_rules('first_field','First Field', 'trim | required | is_natural');

$ this-> form_validation-> set_rules('second_field','Second Field', 'trim | required | is_natural_no_zero');

但是,如何驗證上述第3和第4條件?

在此先感謝。

回答

16

感謝dm03514。我通過下面的回調函數得到它的工作。

$this->form_validation->set_rules('first_field', 'First Field', 'trim|required|is_natural'); 
$this->form_validation->set_rules('second_field', 'Second Field', 'trim|required|is_natural_no_zero|callback_check_equal_less['.$this->input->post('first_field').']'); 

和回調函數是:

function check_equal_less($second_field,$first_field) 
    { 
    if ($second_field <= $first_field) 
     { 
     $this->form_validation->set_message('check_equal_less', 'The First &amp;/or Second fields have errors.'); 
     return false;  
     } 
     else 
     { 
     return true; 
     } 
    } 

一切似乎罰款現在的工作:)

4

您可以編寫自己的驗證功能3,和4個使用回調

http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#callbacks

來自實例文檔

<?php 

class Form extends CI_Controller { 

    public function index() 
    { 
     $this->load->helper(array('form', 'url')); 

     $this->load->library('form_validation'); 

     $this->form_validation->set_rules('username', 'Username', 'callback_username_check'); 
     $this->form_validation->set_rules('password', 'Password', 'required'); 
     $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); 
     $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]'); 

     if ($this->form_validation->run() == FALSE) 
     { 
      $this->load->view('myform'); 
     } 
     else 
     { 
      $this->load->view('formsuccess'); 
     } 
    } 

    public function username_check($str) 
    { 
     if ($str == 'test') 
     { 
      $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"'); 
      return FALSE; 
     } 
     else 
     { 
      return TRUE; 
     } 
    } 

} 
?> 
+1

但是,如何傳遞迴調函數中的其他字段值?在CI文檔中,$ str在回調函數中設置爲'test';但我需要將第一個字段值傳遞給第二個字段的回調函數。 – 2013-03-13 15:36:45

0

如果您正在使用HMVC和接受的解決方案不工作,然後 添加在控制器初始化後的下列行

$this->form_validation->CI =& $this; 

所以它將在您的控制器中爲

$this->load->library('form_validation'); 
$this->form_validation->CI =& $this;