S. M. Shahinul Islam
S. M. Shahinul Islam

Reputation: 2800

custom form validation going wrong in codeigniter

My custom function is not working. I am checking if passed value does not exist in the database it return error message. What I am doing wrong?
Controller function

function sp_exists($str)
        {
            $this->user_model->sp_exists($str);
            $this->form_validation->set_message('sp_exists', 'The %s field does not exists');
        }

Model function

function sp_exists($str)
    {
        $this->db->where('member_id',$str);
        $query = $this->db->get('user');
        if ($query->num_rows() > 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

callback function

$this->form_validation->set_rules('sponsor_id', 'Sponsor ID', 'trim|required|xss_clean|callback_sp_exists');

Upvotes: 0

Views: 180

Answers (2)

Laurence
Laurence

Reputation: 60040

change

function sp_exists($str)
    {
        $this->user_model->sp_exists($str);
        $this->form_validation->set_message('sp_exists', 'The %s field does not exists');
    }

to

function sp_exists($str)
    {
        $this->form_validation->set_message('sp_exists', 'The %s field does not exists');
        return $this->user_model->sp_exists($str);
    }

Upvotes: 0

Mischa
Mischa

Reputation: 43298

Did you look at the user guide? It explains clearly how to do this.

First of all I think you should change the model function to this:

function sp_exists($str)
{
  $this->db->where('member_id',$str);
  $query = $this->db->get('user');
  return $query->num_rows() > 0;
}

And the controller should look like this:

function sp_exists($str)
{
  if(!$this->user_model->sp_exists($str))
  {
    $this->form_validation->set_message('sp_exists', 'The %s field does not exists');
    return FALSE;
  }
  else
  {
    return TRUE;
  }
}

Upvotes: 5

Related Questions