is_unique for codeigniter form validation

前端 未结 9 1104
走了就别回头了
走了就别回头了 2020-12-03 07:19

I\'m trying to figure out how I can use the is_unique rule from the Codeigniter form validation library in the following situation.

I\'m trying to submi

9条回答
  •  广开言路
    2020-12-03 07:57

    Extend Form_validation.php library create class inside of application/libraries file name MY_Form_validation.php

    ci =& get_instance();
            }
    
                    public function is_unique_update($str, $field){
                    $explode=explode('@', $field);
                    $field_name=$explode['0'];
                    $field_id_key=$explode['1'];
                    $field_id_value=$explode['2'];
                    sscanf($field_name, '%[^.].%[^.]', $table, $field_name);
    
                     if(isset($this->ci->db)){
                            if($this->ci->db->limit(1)->get_where($table, array($field_name => $str,$field_id_key=>$field_id_value))->num_rows() === 0){
                                 $this->ci->form_validation->set_message('is_unique_update', 'The {field} field must contain a unique value.');
                                return false;
                            }
                            return true;
                        }
    
    
                }
    }  
    

    Now in your controller

    $this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean|is_unique_update[users.user_name@id@'.$id.']');  
    

    "@" I used for explode the string
    where id is primary key of users table
    and $id is the value of id. Now you can use this is_unique_update validation in any controller.

提交回复
热议问题