CodeIgniter Forums
validation class and callback functions. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: validation class and callback functions. (/showthread.php?tid=19012)



validation class and callback functions. - El Forum - 05-25-2009

[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


validation class and callback functions. - El Forum - 05-25-2009

[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


validation class and callback functions. - El Forum - 05-25-2009

[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;
}