2013-03-12 89 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;