Codeigniter -复选框表单验证


Codeigniter - checkbox form validation

对于一个有多个复选框的表单,我有一个表单验证规则:

$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');

如果我的复选框在提交时都没有被选中,我的代码永远不会通过验证->运行,因为变量不存在:

if ($this->form_validation->run()):

如果我在我的验证规则中加入了对var的检查,验证将永远不会通过,因为没有其他表单验证规则:

if(isset($_POST['groupcheck'])):
   $this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
endif;

我如何管理一个复选框验证规则,其中var可能不存在,它将是唯一的表单变量?

认为,本。

不要在CodeIgniter中使用isset(),因为CodeIgniter提供了更好的类来检查您正在检查的POST变量是否存在,例如尝试使用此代码而不是您的代码:

if($this->input->post('groupcheck')):
   $this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
endif;

关于如何在CodeIgniter中使用POST和GET变量的指南,请查看用户指南:http://codeigniter.com/user_guide/libraries/input.html

我也有同样的问题。如果你的复选框是未选中的,那么它将永远不会被张贴。删除复选框的set_rules,在其他表单验证规则之后,尝试如下内容:

    if ($this->form_validation->run() == TRUE){ // form validation passes 
        $my_checkbox_ticked = ($this->input->post('my_checkbox')) ? yes : no;

您可以将validation_errors()$this->form_validation->run()进行比较,如果是FALSE则没有任何验证,因此您可以做些什么或显示警告

if ($this->form_validation->run() == FALSE) {
    if (validation_errors()) {
        echo validation_errors();
    } else {
        echo 'empty';
    }
}

您还需要设置按钮提交

    $this->form_validation->set_rules('terminos_form', 'TERM', 'required');
    $this->form_validation->set_rules('terminosbox', 'TERM BOX', 'callback__acept_term');

回调

    function _acept_term($str){
        if ($str === '1'){ 
            return TRUE;
        }
            $this->form_validation->set_message('_acept_term', 'Agree to the terms');
            return FALSE;
}
HTML

<input type="checkbox" name="terminosbox" value="1"/>
<button type="submit" name="terminos_form" value="1">NEXT</buttom>