开发者

Codeigniter form validation (mysql check)

开发者 https://www.devze.com 2023-03-09 20:26 出处:网络
I\'m learning CI as we speak, and I\'ve got a quick question for you guys. I\'m currently using the form_validation function to help me with some quick validations. This works fine, but! If i wanted t

I'm learning CI as we speak, and I've got a quick question for you guys. I'm currently using the form_validation function to help me with some quick validations. This works fine, but! If i wanted to validate a username or email that is already in use, how can i do this?

I'm guessing that i need a model and a method that check's if the username or email is开发者_如何转开发 already in use. But how can i combine the false/true result given with the form_validation error messages?


In codeigniter the validation system supports callbacks, this permits you to extend the validation class to meet what you need, for example:

In your controller, change the "username" rule to this:

$this->form_validation->set_rules('username', 'Username', 'callback_username_check');

Then in your controller you can add a function called "username_check":

function username_check($str)
{
    $this->load->model('your_model');

    if ($this->your_model->checkUsername($str))
    {
        return true;
    }
    else
    {
        $this->form_validation->set_message('username_check', 'The username %s already exist');            
        return false;
    }

And in your model:

function checkUsername($username)
{
    $this->db->where('username', $username);
    $query = $this->db->get('users');
    if ($query->num_rows() > 0){
        return true;
    }
    else{
        return false;
    }
}

Bye!!


than you need to use custom callbacks, these are validation functions that you write yourself. You can learn more about it in the codeigniter documentation

0

精彩评论

暂无评论...
验证码 换一张
取 消