Welcome Guest, Not a member yet? Register   Sign In
Passing Parameter in Validation Callback
#1

[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?
#2

[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]';




Theme © iAndrew 2016 - Forum software by © MyBB