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

问题描述 投票:0回答:3

如何在其他字段的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帮帮我!

php codeigniter
3个回答
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
投票

代替

'greater_than[field_one]'

使用

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

我只是尝试了它,它的工作原理。感谢Aritra


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查看
© www.soinside.com 2019 - 2024. All rights reserved.