CodeIgniter Validation in Library does not accept

2019-02-24 05:10发布

my problem is the following: I am writing a login library. This library has a function _validation() and this uses the validation library to validate the data. With using normal validation methods it works just fine, but using a callback function just does not work. It is not called.

I call it like this.

$this->CI->form_validation->set_rules('user', 'Username', 'required|callback__check_user');

The functions name is _check_user and it uses the username _check_user($user). The function itself works fine and I can also call it in the class ($this->_check_user('username')) with a working result.

I am guessing, there might be a problem because I am not workin in a controller so I have a CI instance $this->CI instead of just the original instance $this->

Does anyone have a clue how to fix this?

Thanks in advance.

2条回答
聊天终结者
2楼-- · 2019-02-24 05:42

The form validation callback will only fire on a method inside the current controller.

Just do this in the controller you're using the callback:

function _check_user($user)
{
    $this->load->model('login');
    $result = $this->login->_check_user($user);
    return $result;
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-24 06:03

Hey, I figured out a way that works for me. By just extending the Form_validation library in MY_Form_validation.php you can create custom validation methods. I think it is a clean way and it works perfectly fine. I build the below validation method to check for existing usernames and passwords. $value is something like table_name.fieldname. I have not message set so that it will use the _exist messages from the lang files.

/**
 * Exist
 *
 * checks if the entry exists in the database
 * returns a boolean
 *
 * @access  private
 * @param   string
 * @param   field
 * @return  boolean
 */
function _exist($str, $value)
{       
    list($table, $column) = explode('.', $value, 2);    
    $query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $column = '$str'");
    $row = $query->row();
    return ($row->count > 0) ? TRUE : FALSE;
}

Thanks for your help though.

查看更多
登录 后发表回答