未显示Codeigniter验证错误

时间:2016-08-05 07:41:07

标签: php codeigniter

我的codeigniter验证错误没有显示有人可以提供帮助吗? 我的代码是

public function addProduct(){
    $this->load->view('header', $this->data);
    $this->load->view('product/addProduct');
    $this->load->view('footer');

        $this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
        $this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
        if (!$this->form_validation->run() == FALSE)
        {
            // some stuff on validation success
        }
        else{
            $this->load->view('product/addProduct');
        }

}

我添加了  echo validation_errors();在我看来,表单的行为是product / addProduct。

2 个答案:

答案 0 :(得分:1)

试试这个为你工作。

form_error()函数返回表单错误。

        $post_fields = $this->input->post();
        $data['msg'] = '<ul>';
        foreach ($post_fields as $k => $v) {
            if (form_error($k))
                $data['msg'] .= "<li>" . strip_tags(form_error($k)) . "</li>\n";
        }
        $data['msg'].='</ul>';
        $this->load->view('product/addProduct',$data);

echo validation_errors();//this function also return form  error.

答案 1 :(得分:0)

在视图示例

<?php echo validation_errors('<div class="error">', '</div>'); ?>

<!-- lower case for the controller name on form open -->

<?php echo form_open_multipart('product/addProduct');?>

<h5>productName</h5>
<input type="text" name="productName" value="<?php echo set_value('productName'); ?>" size="50" />

<h5>productPrice</h5>
<input type="text" name="productPrice" value="<?php echo set_value('productPrice'); ?>" size="50" />

<div><input type="submit" value="Submit" /></div> 

<?php echo form_close();?>

控制器

确保您的文件名和类名如下所示,其中首字母大写

Guide

文件名:Product.php

<?php

class Product extends CI_Controller {

 public function __construct() {
    parent::__construct();
    $this->load->library('form_validation');
    $this->load->helper('form');
    $this->load->helper('url');
 }

 public function addProduct(){

    // You can get data from here also

    $this->data['some'] = 'Blah';

    $this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
    $this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');

    // remove your !

    if ($this->form_validation->run() == FALSE){

        // You can just display view in this area you do not have to load it multiple times

        $this->load->view('header', $this->data);
        $this->load->view('product/addProduct');
        $this->load->view('footer');

    } else {

        // some stuff on validation success
    }

 }

}

另外,请检查您是否已在config.php中设置了基本网址,这在CI3版本中是必需的。