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;
}
CodePudding user response:
Your method is not being triggered because your customer_id
field is submitted empty. Codeigniter does not validate empty fields unless the rule is one of required
/isset
/matches
or a callback or a callable. (See Form_validation.php
line 700.)
If you specify your rule as a callable it can remain in the model and will be executed, even if the field is submitted empty:
$this->form_validation->set_rules('customer_id', 'Customer', array(
array($this->your_model, 'customer_required')
));
(See also: 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;
}
And to add the message, use:
$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');