代码点火器表单验证大于字段一,小于字段二


Codeigniter form validation greater than field one and less than field two

如何在Codeigniter中基于其他字段创建表单验证,例如我有两个字段(field_one和field_two),其中field_one必须小于field_two,field_to必须大于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字段2 4

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

而不是

'greater_than[field_one]'

使用

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

我刚试了一下,效果很好。感谢Aritra

像一样尝试

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

Native 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中进行检查