Codeigniter单选按钮表单验证?

时间:2017-04-21 11:50:18

标签: codeigniter

我想使用codeigniter表单验证规则验证三个单选按钮输入...但是,我不知道该怎么做...请帮助...

HTML页面

<form action="<?php echo base_url('register')" ?> method="POST">

    <input type="radio" name="cars" value="BMW">
    <input type="radio" name="cars" value="Ferrari">
    <input type="radio" name="cars" value="Jaguar">

    <input type="submit" name="submitter">

</form>

控制器

public function register()
{

    $this->form_validation->set_rules('cars', 'Cars', 'required');

    if($this->form_validation->run() == TRUE)
    {
        i know what to do here
    }
    else
    {
        i know what to do here
    }
}

如何在codeigniter中为我的案例中的单选按钮进行表单验证?请帮忙... 提前谢谢......

2 个答案:

答案 0 :(得分:0)

在application / config / autoload.php

中加载表格验证和其他助手的库
$autoload['libraries'] = array('form_validation');

$autoload['helper'] = array('form', 'url');

在您的控制器中

public function register()

{

    $this->form_validation->set_rules('cars', 'Cars', 'required');

     if($this->form_validation->run() == TRUE)
    {
        echo "success";
    }
    else
    {
        $this->load->view('welcome_message');
    }
}

在您的视图文件中使用以下代码打印验证错误

<?php echo validation_errors(); ?>

答案 1 :(得分:0)

要显示表单错误,请使用form_error()函数并显示所有错误使用<?php echo validation_errors(); ?>

HTML PAGE

<form action="<?php echo base_url('register'); ?>" method="POST">
    <?php echo form_error('cars'); ?>
    <input type="radio" name="cars" value="BMW">
    <input type="radio" name="cars" value="Ferrari">
    <input type="radio" name="cars" value="Jaguar">

    <input type="submit" name="submitter">

</form>

控制器

public function register(){

    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');

    $this->form_validation->set_rules('cars', 'Cars', 'required');

    if($this->form_validation->run() == TRUE)
    {
        echo "i know what to do here"; //die;
    }
    else
    {
        echo "i know what to do here"; //die;
    }
    $this->load->view('welcome_message'); // your html view page
}