CodeIgniter中的表单验证

时间:2012-02-08 04:27:25

标签: php codeigniter codeigniter-2

我正在使用CodeIgniter的表单验证,它工作正常,但是当表单验证失败时,它不显示验证错误,通过使用 <?php echo validation_errors();?> 我正在使用

function insertProduct(){
        $this->load->library('form_validation');
        $this->form_validation->set_rules('pname','ProductName','trimirequired');
        if($this->form_validation->run()){
            $this->addProduct();
        }
        else{
            $this->load->model('inventory/stock');
        }

请帮助我,我是codeIgniter的新手

4 个答案:

答案 0 :(得分:0)

在您的视图中,您应该有类似的内容(此示例单独显示错误);

<?php echo form_error('p_name'); ?>
<label for="p_name">Product Name</label>
<input type="text" id="p_name" name="p_name" value="<?php echo set_value('p_name'); ?>" />

答案 1 :(得分:0)

您需要告诉控制器中的方法呈现表单验证成功/失败的视图。

如果您将 insertProduct 方法更改为以下内容,则“应该”解决您的问题。

function insertProduct(){
    $this->load->library('form_validation');
    $this->form_validation->set_rules('pname','ProductName','trimirequired');
    if($this->form_validation->run()){
        $this->addProduct();
        $this->load->view('{name_of_your_view}');
    } else{
        $this->load->model('inventory/stock');
        $this->load->view('{name_of_your_view}');
    }
}

其中'name_of_your_view'是您已将 validation_errors()代码放入的视图。

答案 2 :(得分:0)

CodeIgniter教程页面中的这个示例解释了如何验证提交的数据以在表单的标题处显示验证错误,如您所料:

http://codeigniter.com/user_guide/tutorial/create_news_items.html

创建函数的示例代码如下所示:

public function create()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    $data['title'] = 'Create a news item';

    $this->form_validation->set_rules('title', 'Title', 'required');
    $this->form_validation->set_rules('text', 'text', 'required');

    if ($this->form_validation->run() === FALSE)
    {
        $this->load->view('templates/header', $data);   
        $this->load->view('news/create');
        $this->load->view('templates/footer');

    }
    else
    {
        $this->news_model->set_news();
        $this->load->view('news/success');
    }
}

正如其他人所说,你需要添加一个视图来处理成功并将它们返回到表单以显示失败时的错误。

答案 3 :(得分:0)

我们可以更改包含以下代码的行:

$this->form_validation->set_rules('pname','ProductName','trimirequired');

为:

$this->form_validation->set_rules('pname','ProductName','trim|required');
if($this->form_validation->run($this) == false)
{
   $this->addProduct();
}