Codeigniter中的表单验证错误

时间:2013-10-19 22:09:01

标签: php codeigniter validation

我一直关注Envato关于Tutplus的这个教程:https://tutsplus.com/course/build-a-cms-in-codeigniter/。我正处于我要验证登录表单的部分。我的问题是我不能在登录系统中使用我的表单验证规则。我的代码如下:

user_m.php

<?php 
  class User_M extends MY_Model {

public $rules = array(  // I can't use this rules in my controller
   'email' => array(  // for email 
    'field' => 'email',
    'label' => 'Email',
    'rule'  => 'trim|required|valid_email|xss_clean'
    ),
    'password' => array(  // for password
    'field' => 'password',
    'label' => 'Password',
    'rule'  => 'trim|required'
     )
);

}

user.php的

 <?php 

class User extends Admin_Controller {

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

public function login()
{   
   // Set form
   $rules = $this->user_m->rules; // get the value from user_m model and it works well
       // this is not works. this is my problem
   $this->form_validation->set_rules($rules);  

       // if we use this comment code then it works
   //$this->form_validation->set_rules('email', 'Email', 'rim|required|valid_email|xss_clean'); 
   // $this->form_validation->set_rules('password', 'Password', 'required');

   // Process form
   if ( $this->form_validation->run() == TRUE )  { // show the error msg if form problem occurs 
       // We can login and redirect

    }

}

2 个答案:

答案 0 :(得分:0)

您可以尝试此操作(在调用form_validation->run()功能之前在控制器中设置规则)

public function login()
{
    $this->form_validation->set_rules('email', 'Email',  'trim|required|valid_email|xss_clean');
    $this->form_validation->set_rules('password', 'Password',  'trim|required');
    if ( $this->form_validation->run() )  {
        // validation passed
    }
    else {
        // validation failed
    }
}

答案 1 :(得分:0)

您确保在电子邮件和密码文本框下面写了 form_error('email'); form_error('password'); 。     如果发生验证错误,请调用登录视图。

public function login()
{
   $this->form_validation->set_rules('email', 'Email',  'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('password', 'Password',  'trim|required');
   if ($this->form_validation->run() == FALSE)
        {
           **$this->load->view('login view path');**
        }else{write other code of redirect or any.....} 
}