CyberJunkie
CyberJunkie

Reputation: 22674

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?

Upvotes: 2

Views: 2069

Answers (2)

Ivan Ivanic
Ivan Ivanic

Reputation: 3044

$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_                                     ↑

Upvotes: 0

user482594
user482594

Reputation: 17486

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

Upvotes: 1

Related Questions