CodeIgniter Forums
Passing Parameter in Validation Callback - 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: Passing Parameter in Validation Callback (/showthread.php?tid=10648)



Passing Parameter in Validation Callback - El Forum - 08-07-2008

[eluser]Lucas3677[/eluser]
I created a validation callback function that checks a string against a regular expression to save me time from creating small, similar functions like one_or_two() or one_two_four_but_not_three(), etc..)

Code:
function _regex($str, $regex)
    {
        if (preg_match($regex, $str))
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

However when I use it through the validation class, it doesn't work:

Code:
$rules['signuptype'] = 'required|callback__regex[/^(1|2)$/]';

What am I doing wrong?


Passing Parameter in Validation Callback - El Forum - 08-08-2008

[eluser]Lucas3677[/eluser]
So I figured it out. The problem was that CodeIgniter uses | as the delimiter when it explode()s the rules into an array. Another issue I had later on was that when searching for the parameter, CodeIgniter uses the lazy .*? search so when I did "[12]{1}" the ] was being read as the end of the parameter. Here is the solution for your reference:

Code:
function regex($str, $regex)
    {
        $regex = str_replace('#OR#', '|', $regex);
        $regex = str_replace('#OS#', '[', $regex);
        $regex = str_replace('#CS#', ']', $regex);
        
        if (preg_match($regex, $str, $matches))
        {
        
            return TRUE;
        }
        else
        {
            $this->set_message('regex', 'The %s field has an incorrect value.');
            return FALSE;
        }
    }

Code:
$rules['oneortwo'] = 'required|callback_regex[/^(1#OR#2)$/i]';