表单验证在codeIgniter中无法正常工作

时间:2017-11-21 10:14:09

标签: php codeigniter

我创建了一个员工控制器,用于将数据插入数据库,我希望在将数据插入数据库之前设置验证。

我尝试过以下方式,但每次显示message field is required,即使我在文本框中填写了值。

1)控制器

<?php
class Employee_controller extends CI_Controller {
    function __construct() { 
         parent::__construct(); 
         $this->load->helper('url'); 
         /* Load form validation library */ 
         $this->load->library('form_validation');
                $this->load->library('email');
         $this->load->library('session'); 
         $this->load->helper('form'); 
         $this->load->database(); 
    }


    function add_employee(){        
        $this->load->view('Employee_add');   

    }

    function insert_emp(){   
     $this->form_validation->set_rules('name', 'Name', 'required'); 
         if ($this->form_validation->run() == FALSE) { 
      $this->load->view('Employee_add'); 
     } else { 
      $this->load->model('Employee_model');
          $inserData = array(
          'name' =>$_POST['emp_name'],
          'salary' => $_POST['emp_salary']
          );

          $this->Employee_model->insert_employee($inserData);
          $emp_list['emp_records']= $this->Employee_model->list_employee();

      $this->load->view('Employee_list',$emp_list);
     }

    }

}

2)型号代码(以下是我的型号代码)

<?php
 class Employee_model extends CI_Model {

      function __construct() { 
         parent::__construct(); 
      } 

      function insert_employee($inserData){
        $this->db->insert('employee',$inserData);

        return true;
      }
 }  
?>

3)查看

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="center">
        <form action="<?php echo site_url('Employee_controller/insert_emp');?>" method="post">
        <?php echo validation_errors(); ?>
            <div class="element">
                <label>Name</label> 
                <input type="text" name="emp_name" value="">
            </div>

            <div class="element">
                <label>Salary</label>   
                <input type="text" name="emp_salary" value="">
            </div>

            <input type="submit" name="submit" value="Add Employee">
        </form>
    </div>

</body>
</html>  
</body>
</html>  

1 个答案:

答案 0 :(得分:3)

检查您的$this->form_validation->set_rules方法,当您的字段为nameemp_name

时,您将通过emp_salary
相关问题