codeigniter 代码触发器:不执行自定义验证

j9per5c4  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(140)

我正在尝试创建我的自定义验证,如果选择了某个选项,则需要客户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;
}
omtl5h9j

omtl5h9j1#

因为customer_id字段提交为空,所以您的方法未被触发。Codeigniter不会验证空字段,除非规则是required/isset/matches或回调或可调用项之一。(请参阅Form_validation.php第700行。)
如果将规则指定为可调用规则,则即使提交的字段为空,该规则也可以保留在模型中并将被执行:

$this->form_validation->set_rules('customer_id', 'Customer', array(
    array($this->your_model, 'customer_required')
));

(See另请访问:https://codeigniter.com/userguide3/libraries/form_validation.html#callable-use-anything-as-a-rule)

$this->form_validation->set_rules('customer_is_required', 'Customer', array(
    array($this->customer_model, 'check_customer')
));

public function check_customer($str) {
    return false;
}

要添加消息,请用途:

$this->form_validation->set_rules('customer_is_required', 'Customer', array(
    array('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');

相关问题