CI中的表单验证 - unqiue

表单验证中is_unique的时候直接去数据库查询,但是想排除自己,该怎么处理?
比如我的用户名(unique字段)是甲壳虫、id为1,修改用户信息的时候,如果直接用unique,则直接提示被占用,请问如何能排除自己,又能检验唯一性
即这样的sql来验证唯一性 —— select username from xxx where username='甲壳虫' and id!=1
谢谢诸位了

阅读 3.1k
1 个回答

看源码就知道,CI框架中没有这个功能:

public function is_unique($str, $field)
{
    sscanf($field, '%[^.].%[^.]', $table, $field);
    return isset($this->CI->db)
        ? ($this->CI->db->limit(1)->get_where($table, array($field => $str))->num_rows() === 0)
        : FALSE;
}

所以只能自己扩展这个方法,例如:

//自定义验证
$id='x';//获取用户ID
$this->form_validation->set_rules('username', 'Username', "callback_username_check[$id]");
//相关方法
public function username_check($username,$id)
{
    //这里处理逻辑
    $info=$this->db->select('username')
    ->where('username',$username)
    ->where('id !=',$id)
    ->get('xxx')
    ->row_array();
    if (!empty($info)){
        $this->form_validation->set_message('username_check', '手机号已存在');
        return FALSE;
    }else{
        return TRUE;
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题