How do I do negative form validation in the encoder?

is_unique

is a form validation that prevents the value from being used in the database. But can I do the opposite? for example, I would like to have a value that exists in the database, so I do the following rules:

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

      

But this seems unfortunate as I expected, any recommendations? Thank you.

+3


source to share


3 answers


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

      

The mymodel.php model

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

      

+2


source


Extend the Form_validation library by adding a class MY_Form_validation.php

to your folder /application/core

(assuming your subclass prefix MY

matches the default). This is a quick example that simply inverts the existing is_unique

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

      

0


source


Try your own callback function

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

      

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

      

0


source







All Articles