【问题标题】:Codeigniter - checkbox form validationCodeigniter - 复选框表单验证
【发布时间】:2011-10-24 08:05:34
【问题描述】:

我为具有多个复选框的表单设置了表单验证规则:

$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 可能不存在并且它将是唯一的表单变量,我该如何管理复选框验证规则?

问候,本。

【问题讨论】:

  • required 是干什么用的?如果您至少需要选中一个复选框,那么您的第一个代码就可以了。如果不需要,只需将其删除...
  • @ldiqual - 感谢您的指点。我删除了“必需”,但当没有选中复选框时它仍然无法运行:code $this->form_validation->set_rules('groupcheck[]', 'groupcheck', ''); if ($this->form_validation->run()): echo "test";
  • 我能想到的唯一选择是在其中放置一个隐藏的表单字段,然后对其进行验证。这样,验证规则将始终通过。不过看起来像个黑客。
  • 你的 if 语句需要有一个 true 或 false 像这样 "if ($this->form_validation->run() == TRUE) " 可能不能解决你的问题,但这是一个好习惯跨度>

标签: php forms validation codeigniter checkbox


【解决方案1】:

还需要设置按钮提交

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

【讨论】:

    【解决方案2】:

    您可以在$this-&gt;form_validation-&gt;run() 之后比较validation_errors(),如果是FALSE,则没有任何验证,因此您可以执行某些操作或显示警告

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

    【讨论】:

      【解决方案3】:

      我有同样的问题。 如果您的复选框未选中,那么它将永远不会被发布。删除复选框的 set_rules 并在其他表单验证规则之后,尝试类似:

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

      【讨论】:

        【解决方案4】:

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

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

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

        【讨论】:

        • 感谢您的指点,但我不确定如果未设置 var,我的表单验证将如何运行。它仍然会失败:code if ($this->form_validation->run()): code
        • 它失败了,因为您将 groupcheck 设置为 required,这使得 groupcheck 复选框被选中,因为它是必需的,所以至少应该选中一个。
        猜你喜欢
        • 2014-03-12
        • 2013-01-05
        • 2021-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-01
        • 1970-01-01
        • 2017-05-04
        相关资源
        最近更新 更多