How to do a negative form validation in codeigniter?

前端 未结 3 1584
走了就别回头了
走了就别回头了 2021-01-18 09:27

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 w

相关标签:
3条回答
  • 2021-01-18 09:39

    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();
    }
    
    0 讨论(0)
  • 2021-01-18 09:42

    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;
            }
        }
    
    0 讨论(0)
  • 2021-01-18 10:02

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题