【问题标题】:Codeigniter: Form Validation still fails when checkbox is checkedCodeigniter:选中复选框时表单验证仍然失败
【发布时间】:2021-11-19 15:45:29
【问题描述】:

我想知道为什么我的复选框即使在它已经被勾选后仍然失败。它是条款和条件的复选框

控制器:

// Load the registration page
public function registration_page(){
    $this->load->view('includes/main_index');
    $this->load->view('recycler/forms/register');
    $this->load->view('includes/footer');
}

public function accept_terms_conditions()
    {
 //    Checkbox name is 'agree' which checks if the value of $checked
 //    is equal to 1 
        $checked = $this->input->post('agree');
        return (int) $checked == 1 ? TRUE : FALSE;
    }

$this->form_validation->set_rules('agree', '', 'callback_accept_terms_conditions');
if($this->form_validation->run() == FALSE)
{
   // After form submission, it always goes here
   $this->registration_page();
} 
else{ /* Proceed to data insertion */ }

我使用 print_r 函数打印了它的 post 值,它返回 1,但验证仍然失败。 $this->form_validation->run() == FALSE 表示如果表单验证有错误会回到注册视图,也就是$this->register()方法调用。

print_r

ticked checkbox

有谁知道为什么它总是失败?

编辑: 添加了注册视图的加载方法,即 register() 方法

【问题讨论】:

  • 使用if($this->form_validation->run()){}else{}
  • 已经试过了,还是不行

标签: php forms codeigniter validation codeigniter-3


【解决方案1】:

试试

public function accept_terms_conditions() {
  $checked = ($this->input->post('agree')) ? TRUE : FALSE;
  return $checked;
}

【讨论】:

    【解决方案2】:

    复选框在选中时将“on”作为值而不是 1。

    public function accept_terms_conditions()
    {
    // returns true if the checkbox 'agree' has been checked 
     return ($this->input->post('agree') === 'on');
    }
    

    你的条件是错误的,你是说如果验证失败然后调用方法注册我认为应该是相反的。

    【讨论】:

    • 请解释一下你的代码。
    • 条件没有错,意思是当表单有错误时,它会回到注册视图并显示错误
    • 使用 Kumar 评论的内容
    • 还有 var_dump($this->input->post('agree')) 看看它是否给你 1 而不是“on”
    • 做了 var_dump 并返回一个字符串,在我的方法中我将其转换为整数但它仍然不接受它,Kumar 的答案是一样的,你只是试图反过来验证它。它根本没有改变任何东西
    猜你喜欢
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 2019-03-01
    • 2014-10-10
    相关资源
    最近更新 更多