根据实际需要,进行表单验证类的扩展。CI手册上的方式是写在Controller里面的callback_方法,这样不利于其他地方调用,
而在Model无法调用,这个和方法的调用形式有关系,看下面的代码。
有些验证方法可能我们其他的地方也会用到,所以扩展是非常必要的。
关于Form_validation里面的callback_方法的调用代价可以看下下面的这段代码
// Is the rule a callback? $callback = FALSE; if (substr($rule, 0, 9) == 'callback_') { $rule = substr($rule, 9); $callback = TRUE; } // Strip the parameter (if exists) from the rule // Rules can contain a parameter: max_length[5] $param = FALSE; if (preg_match("/(.*?)\[(.*)\]/", $rule, $match)) { $rule = $match[1]; $param = $match[2]; }
// Call the function that corresponds to the rule if ($callback === TRUE) { if ( ! method_exists($this->CI, $rule)) { continue; } // Run the function and grab the result $result = $this->CI->$rule($postdata, $param); // Re-assign the result to the master data array if ($_in_array == TRUE) { $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result; } else { $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result; } // If the field isn't required and we just processed a callback we'll move on... if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE) { continue; } }
从上面的代码可以看出来:
if ( ! method_exists($this->CI, $rule))
写在Model里面的方法,是不会被调用到的。所以为了方便其他的Controller调用,最好还是采用扩展Form_validation的方式。
我的自定义类的前缀是Ex_(config.php文件里面修改)
class Ex_Form_validation extends CI_Form_validation { function __construct() { parent::__construct(); $this->CI->load->database(); } function username_unique($username) { $this->CI->db->select('username'); $que = $this->CI->db->get_where('member', array( 'username' => $username ), 1); if ($que->num_rows() > 0) { $this->CI->form_validation->set_message('username_unique', lang('f_member_username_unique')); return false; } return true; } }
代码中的lang是采用了语言文件。
这样在set_rules的时候直接这样写即可:
$this->form_validation->set_rules('username', 'lang:f_member_username', 'trim|required|min_length[5]|max_length[20]|alpha_numeric|username_unique');