且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

模型中的Codeigniter表单验证

更新时间:2023-12-03 18:28:52

在模型中做你的表单验证。但是你想让验证返回True或False到你的控制器。不调用视图。所以像

its fine to do your form validation in a model. But you want to have the validation return True or False to your controller. Not call a view. So like

// in your Model lets call it Users
function verify_login()
{    
    $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) {
       return FALSE ; 
    } else {
       return TRUE; 
    }
}

// Your callback function 


 // in Controller 
function verify(){

if( $this->users->verify_login() == FALSE ){  
// $this->errormessage will be available in any view that is called from this controller
$this-errormessage = "There was an error with your Log In. Please try again." ; 
$this->showLogin() ; } 

else { 
// set a session so you can confirm they are logged in on other pages
$this->setLoginSession($this->input->post('username', TRUE)) ; 
$this->showUserHome(); } 
}

另一件要考虑的事 - 通常人们知道他们的用户名,他们的密码。因此,如果您单独检查它们,您可以相应地调整错误消息。如果你检查用户名,没有结果 - 你不需要检查密码,并在错误消息,你可以告诉他们没有该名称的用户。

Another thing to think about -- often people know their user name but mess up their password. So if you check for them separately you can adjust the error message accordingly. And if you check for user name and there are no results -- you don't need to check for password and in the error message you can tell them there is no user by that name.