CodeIgniter: custom validation rules can't be in a helper?

心已入冬 提交于 2019-12-30 12:04:52

问题


I've created a "validation helper" that was supposed to have all my custom validation rules. The problem is that when I use them in my form validation, they seem to be ignored. If I move the functions in the controller that is doing the form validation, everything works like a charm. My validation helper is autoloaded.

Is there any reason why I can't seem to use these validation functions if I put them in a helper? Thanks.


回答1:


A function in a helper and a controller are different obviously.

Create an extended MY_Form_validation.php in your libraries/, add the functions there and finally set the rules without callback_ and just their function name.

Example:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

    /* set_rule('custom_require') */
    function custom_require($str) {

        return (bool)$str;

    }

}



回答2:


Robin's answer is the easiest way to deal with it; however, the why you can't is this:

look in your system/libraries/Form_Validation.php, line: 587

if ( ! method_exists($this->CI, $rule))
{
  continue;
}

This check is done on all callbacks. Helpers are not classes & not loaded into the CI instance - and so not available from the Form_Validation library (because of the way it is specifically coded in this method)



来源:https://stackoverflow.com/questions/10652870/codeigniter-custom-validation-rules-cant-be-in-a-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!