codeigniter中的自定义表单验证出错

时间:2012-05-15 05:14:58

标签: codeigniter validation

我的自定义功能无效。我正在检查数据库中是否存在传递的值,它返回错误消息。我做错了什么? 控制器功能

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

模型功能

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

回调功能

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

2 个答案:

答案 0 :(得分:5)

你看过user guide了吗?它清楚地解释了如何做到这一点。

首先,我认为您应该将模型功能更改为:

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

控制器应如下所示:

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

答案 1 :(得分:0)

变化

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

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