Codeigniter表单验证大于字段1且小于字段2

时间:2016-07-21 02:36:51

标签: php codeigniter

如何在其他字段的Codeigniter中创建表单验证,例如我有两个字段(field_one和field_two),其中field_one必须是less_than field_two而field_to必须是greater_than field_one。

$this->form_validation->set_rules('field_one', 'Field One', 'less_than[field_two]');

$this->form_validation->set_rules('field_two', 'Field Two', 'greater_than[field_one]');

我的代码无效,错误始终显示

'第二场必须大于第一场'

但是我输入正确的方式,

第一场1 第二场4

如何解决这个问题? Plz帮助我!

3 个答案:

答案 0 :(得分:1)

试试这个

    $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; } 
}

答案 1 :(得分:1)

而不是

'greater_than[field_one]'

使用

'greater_than['.$this->input->post('field_one').']'

我只是试了一下它的确有效。感谢Aritra

答案 2 :(得分:1)

本机的Greater_than方法需要数字输入,因此我们不能直接使用Greater_than [field_one]。但是我们可以定制方法来达到目标​​。

我的方法如下:

/* A sub class for validation. */
class MY_Form_validation extends CI_Form_validation {

    /* Method: get value from a field */
    protected function _get_field_value($field)
    {
        return isset($this->_field_data[$field]["postdata"])?$this->_field_data[$field]["postdata"]:null;
    }

    /* Compare Method: $str should >= value of $field */
    public function greater_than_equal_to_field($str, $field)
    {
        $value = $this->_get_field_value($field);
        return is_numeric($str)&&is_numeric($value) ? ($str >= $value) : FALSE;
    }
}

所有验证数据都保存在受保护的变量$ _field_data中,值保存在键“ postdata”中,因此我们可以获取所需字段的值。

使用上述方法时,可以使用'greater_than_equal_to_field [field_one]'在两个字段之间进行验证。

  • 一个很好的参考-本机表单验证方法匹配并且有所不同。您可以在CI_Form_validation
  • 中进行检查