I'm trying to create my custom validation which is customer ID is required if certain option is selected. Right now, I just want to test if the custom validation is working so I don't care about the options and only set message and always return false. I don't want to put the validation in my controller for MVC pattern reason. It doesn't work if my custom validation is put in model, so I created a new validation file in libraries folder called MY_Form_validation.
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;
}
}
in model, I call it like this:
public function save()
{
/* other form validation */
$this->form_validation->set_rules('customer_id', 'Customer', 'customer_required');
return $this->form_validation->run();
}
I also put it in autoload
$autoload['libraries'] = array('session','database','table','form_validation', 'MY_Form_validation');
It should always fail to save because the validation only return false. But it looks like the custom validation is not executed at all because it always return true. Is there something that I missed? It's been days and I still don't know where I did wrong. Please help.
Update
As Marleen suggested, I tried using callable but again, function check_customer doesn't seem executed because I have a successful save.
Customer_model
$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;
}