Welcome Guest, Not a member yet? Register   Sign In
validation class and callback functions.
#1

[eluser]nealumney[/eluser]
I have a callback function I want to call in a number of controllers, something like this:

Code:
function checkpostcode($postcode)
{
    $this->form_validation->set_message('postcode', 'The postcode you entered is not valid');
    return preg_match('^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$');
}
For some reason, if I place this in a 'helper' it does not work, but if it is created within the controller it works.

I call the helper before the validation rules are set thus:
Code:
$this->load->helper('checkpostcode');

And my validation rule array entry looks like this:

Code:
array('field'    => 'postcode','label'    => 'Postcode must be valid','rules'   => 'trim|required|callback_checkpostcode'),

Do validation callbacks have to sit within the controller? Or am I doing something wrong?

Thanks

Neal
#2

[eluser]Dam1an[/eluser]
Yes, callback functionc currently need to be in the scope of the controller Sad
You could always put it in a MY_Controller, then it would be available to all controllers
#3

[eluser]TheFuzzy0ne[/eluser]
- Or you can extend the validation controller and add your custom methods,
- Or you can store your validation rules in a config file (the form validation library supports this natively)
- Or you can extend the validation class, and have it use a model or function or whatever.

It's also possible to just alias the method from your controller:

Code:
function _custom_validation($str="")
{
    if ( ! $this->some_model->validation($str))
    {
        $this->form_validation->set_message('_custom_validation', 'Uh-oh...');
        return FALSE;
    }

    return TRUE;
}

Or:

Code:
function _custom_validation($str="")
{
    if ( ! some_function($str))
    {
        $this->form_validation->set_message('_custom_validation', 'Uh-oh...');
        return FALSE;
    }

    return TRUE;
}




Theme © iAndrew 2016 - Forum software by © MyBB