模型中的Codeigniter表单验证 [英] Codeigniter Form Validation in Model

查看:94
本文介绍了模型中的Codeigniter表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,这是我第一个CI项目。

Hello all, this is my first CI project.

我的模型中有一个简单的表单验证函数。

I have a simple form validation function in my model.

function verify_login()
{

    //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');

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

这只适用于控制器,一个模型。当我尝试将变量从控制器传递给模型中的函数时,变量被接收,但不会被处理。

This only works when it's in a controller but not in a model. When I try passing the variables from the controller to the function in the model, the variables get received but won't process.

有人可以启发我吗?谢谢。

Can someone enlighten me? Thank you.

推荐答案

在模型中做你的表单验证。但是你想让验证返回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.

这篇关于模型中的Codeigniter表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆