How to do a negative form validation in codeigniter?

浪子不回头ぞ 提交于 2019-12-30 20:37:06

问题


is_unique is the form validation which not allow the value exist in the database. But, can I do the opposite one? for example, I would like to need the value which is exist in the database, so, I make the rules like this:

$this->form_validation->set_rules('email', 'Email', 'required|max_length[32]|valid_email|(!(is_unique[users.email]))');

But it seems not success as I expected, any recommends? Thanks.


回答1:


You can do it like this

$this->form_validation->set_rules('email', 'Email', 'required|max_length[32]|valid_email|callback_email_available');

Controller method

public function email_available($str)
{
    // You can access $_POST variable
    $this->load->model('mymodel');
    $result =   $this->mymodel->emailAvailability($_POST['email']);
    if ($result)
    {
        $this->form_validation->set_message('email_available', 'The %s already exists');
        return FALSE;
    }else{
        return TRUE;
    }
}

Model mymodel.php

public function emailAvailability($email)
{
    $this->db->where('email',$email);
    $query  =   $this->db->get('tablename');
    return $query->row();
}



回答2:


Extend the Form_validation library by adding a class like MY_Form_validation.php in your /application/core folder (assuming your subclass prefix is MY, which it is with default settings. This is a quick example, which just inverts the existing is_unique function by changing the last line from return $query->num_rows() === 0;.

class MY_Form_validation extends Form_validation
{
    /**
     * Match one field to others
     *
     * @access  public
     * @param   string
     * @param   field
     * @return  bool
     */
    public function is_not_unique($str, $field)
    {
        list($table, $field)=explode('.', $field);
        $query = $this->CI->db->limit(1)->get_where($table, array($field => $str));

        return $query->num_rows() > 0;
    }
}



回答3:


Try your own callback function

$this->form_validation->set_rules('email', 'Email', 'required|max_length[32]|valid_email|callback_email_check');

Function will be something like this

public function email_check($str)
    {
        if ($str == 'test@test.com')
        {
            $this->form_validation->set_message('email_check', 'The %s field can not be the word "test@test.com"');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }


来源:https://stackoverflow.com/questions/14451297/how-to-do-a-negative-form-validation-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!