Easy way to pass multiple variables to a CodeIgniter validation callback

I was recently working on a custom form validation callback for my CodeIgniter script. By default, one gets the field that you’re validating available in the callback function. For example, if I have the following form validation rule:

 $this->form_validation->set_rules('discountGlobal', 'Global Discount', 'trim|integer|max_length[1]|xss_clean|prep_for_form|only_one_global_discount[]');

My custom callback is only_one_global_discount. I am not explicitly passing anything through to it. However, in the function I have in my MY_Form_validation.php file, I can access the $discountGlobal value:

public function only_one_global_discount($discountGlobal) {
$CI =& get_instance();
echo $discountGlobal;

You can also pass a second value, though. You would change your callback call to:

$this->form_validation->set_rules('discountGlobal', 'Global Discount', 'trim|integer|max_length[1]|xss_clean|prep_for_form|only_one_global_discount['.$test.']');

Where $test is the second value you want available to you in your function. The function call would then change to:

public function only_one_global_discount($discountGlobal, $test) {

And the value of $test would be available to you in the function. But what can you do if you need a third, fourth or even more values? My solution is to package up the variables you need in an array. Just passing through an array just gives me “Array” when using a print_r on it in my callback function. So, I used json_encode on the array before passing it through and then json_decode in my callback function. Viola! I have access to as many variables as I need.

2 thoughts on “Easy way to pass multiple variables to a CodeIgniter validation callback

    1. Thanks for the comment. To be honest, I haven’t tried it in CI 3.1. I will try to give it a shot and report back. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *