我正在尝试创建我的自定义验证,如果选择了某个选项,则需要客户ID。现在,我只想测试自定义验证是否正常工作,所以我不关心选项,只设置消息并始终返回false。我不想出于MVC模式的原因将验证放在我的控制器中。如果将自定义验证放在模型中,它将不起作用。因此我在库文件夹中创建了一个名为MY_Form_validation的新验证文件。
表单验证.php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
protected $CI;
function __construct($rules = array())
{
parent::__construct($rules);
}
public function customer_required($str)
{
$this->set_message('customer_required', 'Customer is required if you choose option A');
return false;
}
}
在建模中,我这样称呼它:
public function save()
{
/* other form validation */
$this->form_validation->set_rules('customer_id', 'Customer', 'customer_required');
return $this->form_validation->run();
}
我还把它装进了自动装弹机
$autoload['libraries'] = array('session','database','table','form_validation', 'MY_Form_validation');
它应该总是无法保存,因为验证只返回false。但它似乎根本没有执行自定义验证,因为它总是返回true。有什么我错过了吗?已经几天了,我仍然不知道我做错了什么。请帮助。
更新
正如Marleen建议的那样,我尝试使用可调用函数,但是函数check_customer似乎没有执行,因为我保存成功了。
客户模型
$this->form_validation->set_rules('customer_is_required', array($this->customer_model, 'check_customer'));
$this->form_validation->set_message('customer_is_required', 'Customer is required of you choose option A');
private function check_customer()
{
return false;
}
1条答案
按热度按时间omtl5h9j1#
因为
customer_id
字段提交为空,所以您的方法未被触发。Codeigniter不会验证空字段,除非规则是required
/isset
/matches
或回调或可调用项之一。(请参阅Form_validation.php
第700行。)如果将规则指定为可调用规则,则即使提交的字段为空,该规则也可以保留在模型中并将被执行:
(See另请访问:https://codeigniter.com/userguide3/libraries/form_validation.html#callable-use-anything-as-a-rule)
要添加消息,请用途: