【问题标题】:Set general form validation error in CodeIgniter在 CodeIgniter 中设置常规表单验证错误
【发布时间】:2012-07-28 16:34:18
【问题描述】:

假设我在 CodeIgniter 中有一个登录表单——我可以为各个输入设置验证规则,但是有没有办法抛出模型/控制器级别的错误和消息?

具体来说,如果下面的方法没有返回 TRUE,我希望我的表单重新显示“电子邮件地址或密码不正确”的消息。目前控制器只是重新加载视图和 set_value()s

public function authorize_user()
{
    $this->db->where('email', $this->input->post('email'));
    $this->db->where('password', $this->input->post('password'));

    $q = $this->db->get('users');

    if($q->num_rows() == 1){
        return true;
    }
}

也许我想多了,我应该将错误消息附加到电子邮件输入中?

【问题讨论】:

    标签: php validation authentication codeigniter


    【解决方案1】:

    您可以使用回调函数来完成此操作。步骤如下:
    1.您的authorize_user()函数必须在您设置规则的控制器中。
    2.您通过添加类似于以下的代码来制定“回调”规则:

    $this->form_validation->set_rules('email', 'email', 'callback_authorize_user['.$this->input->post("password").']');
    

    请注意,我为回调函数添加了一个参数。这类函数自动接收由set_rules() 的第一个参数确定的参数。在这种情况下,自动传递给回调函数的参数是电子邮件。另外,我将密码作为第二个参数传递。

    3.将相应的参数添加到您的函数中:

    public function authorize_user($email,$password)
    {
       //As I said before, the email is passed automatically cause you set the rule over the email field.
        $this->db->where('email', $email);
        $this->db->where('password', $password);
    
        $q = $this->db->get('users');
    
        if($q->num_rows() == 1){
            return true;
        }
    }
    

    更多信息请访问:http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks

    希望对你有帮助!

    【讨论】:

    • 啊,太好了,谢谢。我阅读了有关向回调添加第二个参数的信息,但没有想到以这种方式使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多