doujianzi8521 2012-02-04 07:21
浏览 66
已采纳

在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>

I use that code to validate a filled in form but the browser shows nothing after I submit. The URL of my browser is stuck at http://example.com/index.php/verifylogin

verifylogin.php is defined like this

<?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条回答 默认 最新

  • duanchoupo1104 2012-02-04 14:19
    关注
    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();
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?