DNB5brims
DNB5brims

Reputation: 30578

How to do a negative form validation in codeigniter?

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.

Upvotes: 6

Views: 2490

Answers (3)

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

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

Upvotes: 3

Saleem
Saleem

Reputation: 1049

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 == '[email protected]')
        {
            $this->form_validation->set_message('email_check', 'The %s field can not be the word "[email protected]"');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

Upvotes: 0

Dwight
Dwight

Reputation: 12460

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

Upvotes: 3

Related Questions