开发者

Codeigniter helper function to validation rules

I created a helper for checking if a user id exists in my user database table:

   if ( ! function_exists('valid_user'))
    {
        function valid_user($user_id)
        {
            $ci=& get_instance();
            $ci->load->database(); 

            $ci->db->select('id');
            $ci->db->where('id', $user_id);
            $ci->db->where('activated', 1);
            $ci->db->where('banned', 0);
            开发者_运维问答$ci->db->limit(1);
            $query = $ci->db->get('users');

            if ($query->num_rows() > 0) //if user exists
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
    }

I added the function to my validation rule like so

$this->form_validation->set_rules('user_id', 'User ID', 'required|xss_clean|max_length[11]|is_natural_no_zero|valid_user');

It does not perform the valid_user function. What am I doing wrong here?


In my previous experience, I usually added a validation function (in your case, valid_user) in the same place where the callback is called.

For example, I would put valid_user method in a users_controller where one of the registration methods will invoke the valid_user method.

Also, it seems that, in your set_rules, you have to set callback_valid_user not valid_user according to the Codeigniter user guides.

http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks


$this->form_validation->set_rules('user_id', 'User ID',
'required|xss_clean|max_length[11]|is_natural_no_zero|callback_valid_user');
//note the callback_                                     ↑
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜