Welcome Guest, Not a member yet? Register   Sign In
Passing a dynamic variable as a parameter to a form validation callback function
#1

[eluser]aidehua[/eluser]
Perhaps this is obvious, but it took me a while to get right so I'll post it here in case it's helpful for anyone.

Normally a CodeIgniter form validation callback function takes one parameter, which is passed to it "automatically": the value of that particular form field.

For example:
Code:
function _my_callback_function($field_value){
// Do something to check $field_value, then return TRUE or FALSE
}

With the corresponding validation rule:
Code:
$this->form_validation->set_rules('some_field', 'Some Field Name', 'callback__my_callback_function');

If you want to pass a second parameter (or maybe you'd call it a second argument) to your callback function, you can do it like this:

Callback function:
Code:
function _my_callback_function($field_value, $second_parameter){
// Do something to check $field_value and $second_parameter, then return TRUE or FALSE
}

Validation rule:
Code:
$second_parameter = 'foo';
$this->form_validation->set_rules('some_field', 'Some Field Name',
'callback__my_callback_function[' . $second_parameter . ']');

The thing that wasn't obvious (to me) was to put the parameter in square brackets in the validation rule.

Note I've given my callback function a name that begins with an _underscore, so the validation rule contains a __double underscore. And note that if you're doing this and you want to set a validation message for your callback rule, don't forget the underscore there, too:
Code:
$this->form_validation->set_message('_my_callback_function', 'My message');


Messages In This Thread
Passing a dynamic variable as a parameter to a form validation callback function - by El Forum - 04-02-2010, 08:29 AM



Theme © iAndrew 2016 - Forum software by © MyBB