在CodeIgniter中设置常规表单验证错误



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

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

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;
    }
}

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

您可以使用回调函数来实现这一点。步骤如下:
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

希望它能有所帮助!

最新更新