您可以callback_
在规则中使用,参见回调.
$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member');
并在控制器中添加该方法.此方法需要返回TRUE或FALSE
function validate_member($str) { $field_value = $str; //this is redundant, but it's to show you how //the content of the fields gets automatically passed to the method if($this->members_model->validate_member($field_value)) { return TRUE; } else { return FALSE; } }
然后,您需要在验证失败时创建相应的错误
$this->form_validation->set_message('validate_member','Member is not valid!');
实现这一目标的最佳方法是扩展CodeIgniter的表单验证库.假设我们要创建一个以数据库表access_code_unique
字段命名的自定义验证器.access_code
users
您所要做的就是创建一个MY_Form_validation.php
在application/libraries
目录中命名的类文件.该方法应始终返回TRUE
ORFALSE
CI =& get_instance(); } public function access_code_unique($access_code, $table_name) { $this->CI->form_validation->set_message('access_code_unique', $this->CI->lang->line('access_code_invalid')); $where = array ( 'access_code' => $access_code ); $query = $this->CI->db->limit(1)->get_where($table_name, $where); return $query->num_rows() === 0; } }
现在,您可以轻松添加新创建的规则
$this->form_validation->set_rules('access_code', $this->lang->line('access_code'), 'trim|xss_clean|access_code_unique[users]');