CodeIgniter:如何将自定义验证函数放在模型中而不是控制器中


CodeIgniter: How to put custom validation function in model instead of controller?

在CI的文档中,它说您可以创建自己的自定义验证,用于表单提交检查。它展示了如何在控制器中做到这一点:

http://ellislab.com/codeigniter%20/user-guide/librarys/form_validation.html

但是,如果我想在模型中具有自定义验证功能,该怎么办

我发现以下内容不起作用。。。

以下两个功能都在一个模型中:

public function validate_form(){
  $this->form_validation->set_rules('username', 'Username', 'callback_illegal_username_check');
  $this->form_validation->run();
}

这是我的自定义验证功能:

public function illegal_username_check($string){
  if($string == 'fcuk'){
    $this->form_validation->set_message('illegal_username_check', 'Looks like you are trying to use some swear words in the %s field');
    return FALSE;
  }
  else{
   return TRUE;
  }
}

我发现,因为我的自定义验证函数在模型中,所以当我运行"validate_form()"函数时,它没有被调用。如何解决此问题?

非常感谢!

您应该将自定义验证规则放在application/libraries文件夹中的MY_Form_validation.php中。

然后,当你分配规则时,你可以做这样的事情。。

 $this->form_validation->set_rules('field1', 'Field one name', 'trim|required|xss_clean|your_custom_validator');

请注意,自定义验证器不需要前面有callback_关键字。

下面是一个示例My_Form_valdation.php文件。

class MY_Form_validation extends CI_Form_validation {
 function __construct($rules = array()) {
    parent::__construct($rules);
    $this->ci = & get_instance();
    $this->ci->load->database();
}
function your_custom_validator($val) {

    $this->set_message('your_custom_validator', 'this isn''t right!');
    return (!$val) ? FALSE : TRUE;
}

请注意,在构造中,我已经获得了Ci实例并加载了数据库类。

要使用它,我会做这样的事情。。

  $this->ci->db->where('id', 1)->get('user')->row();