views:

23

answers:

2

Hi, I have some basic validation of some variables, but it is repeated on more than one page, how can I create a validation file and call it when needed? Here is some code:

$rep = '';
$clean_rep = '';
$rep = $_GET[rep];

//Basic Variable Validation
switch ($rep){
    case 'All':
    case 'Ian':
    case 'Mike':
    case 'Stan':
    case 'Gena':
        $clean_rep = $rep;  
        break;
}

If I put this in a separate file and included it on the needed pages, I assume it would have to be in a function so it can be singled out:

validation.php:
function validateRep($rep){
    switch ($rep){
        case 'All':
        case 'Ian':
        case 'Mike':
        case 'Stan':
        case 'Gena':
            $return("Clean");
            break;
    }
}

once the variable is returned as "Clean", do I just assign $rep in the first script to $clean_rep? or is there a better procedure to doing this?

A: 

You can do it like this:

function validateRep($rep)
{
    switch ($rep)
    {
        case 'All':
        case 'Ian':
        case 'Mike':
        case 'Stan':
        case 'Gena':
            $return($rep);
            break;
    }
    return null;
}

And in your main code files:

$rep = validateRep($rep);
shamittomar
Thanks, is this sort of validation good enough? Or should I be adding more?
Murtez
+1  A: 

validation.php:

function validateRep($rep){
    return in_array($rep, array(
        'All', 'Ian', 'Mike', 'Stan', 'Gena', 
    ));
}

[in_array][1] would check if first parameter exists in the second array parameter, and return true if it exists, false if it's not, and the validateRep function would return the returned value in turn. so when calling, you'll get true if it's valid, false if it's not.

aularon
Is there an advantage to this method as opposed to the other? Aside from being more compact?
Murtez
It's easier to update, and makes use of internal language `in_array` call, which executes fast. also it returns either true or false, which makes more sense in this example (it is either valid or not valid), and will be easier to work with as return values, whether inside `if` checks or other places.
aularon