在codeigniter中进行表单验证

时间:2012-02-04 07:21:32

标签: php codeigniter

<?php echo validation_errors(); ?>
<?php echo form_open('verifylogin'); ?>
  <label for="username">Username:</label>
  <input type="text" size="20" id="username" name="username"/>
  <br/>
  <label for="password">Password:</label>
  <input type="password" size="20" id="password" name="password"/>
  <br/>
  <input type="submit" value="Login"/>
</form>

我使用该代码验证填写的表单,但浏览器在提交后没有显示任何内容。我的浏览器的网址停留在http://example.com/index.php/verifylogin

verifylogin.php定义如下

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.&nbsp; User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
     redirect('home', 'refresh');
   }

 }

 function check_database($password)
 {
   //Field validation succeeded.&nbsp; Validate against database
   $username = $this->input->post('username');

   //query the database
   $result = $this->user->login($username, $password);

   if($result)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'id' => $row->id,
         'username' => $row->username
       );
       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?>

1 个答案:

答案 0 :(得分:1)

class Auth extends CI_Controller{

    public function __construct(){parent::__construct();}
     /**
     * Login Form
     *
     * $route['login'] = 'auth/login_form';
     *
     */
    public function login_form(){
         $this->load->view('login_form');
    }
    /**
     * Login Validation
     *
     * $route['login/check'] = 'auth/login_check';
     * Point your form to login/check
     */
    public function login_check()
    {
        if($this->form_validation->run() == TRUE)
        {
            //form validates...
        }else
        {
             //no redirect! just show for again!
             $this->login_form();
        }
    }
}