Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP form validation function

I am currently writing some PHP form validation (I have already validated clientside) and have some repetitive code that I think would work well in a nice little PHP function. However I am having trouble getting it to work. I'm sure it's just a matter of syntax but I just can't nail it down.

Any help appreciated.

//Validate phone number field to ensure 8 digits, no spaces.
if(0 === preg_match("/^[0-9]{8}$/",$_POST['Phone']) {
    $errors['Phone'] = "Incorrect format for 'Phone'";
}

if(!$errors) {
    //Do some stuff here....
}

I found that I was writing the validation code a lot and I could save some time and some lines of code by creating a function.

//Validate Function
function validate($regex,$index,$message) {
    if(0 === preg_match($regex,$_POST[$index])) {
        $errors[$index] = $message;
    }

And call it like so....

validate("/^[0-9]{8}$/","Phone","Incorrect format for Phone");

Can anyone see why this wouldn't work?

Note I have disabled the client side validation while I work on this to try to trigger the error, so the value I am sending for 'Phone' is invalid.

like image 671
Barbs Avatar asked Dec 19 '12 05:12

Barbs


2 Answers

Let's try something a little more thought out.

You want to use this like so:

if (validate(...)) {
    // It's ok
}

Then I'd suggest this:

function validate($regex, $index, $message, &$errors) {     
    if (isset($_POST[$index]) && 1 === preg_match($regex, $_POST[$index])) {
        return true;            
    }
    $errors[$index] = $message; 
    return false;        
}

Now you have an opportunity to dump out of validation on error, or you can chain through these passing in the $errors and fill it with validation errors. No globals used.

like image 104
gview Avatar answered Sep 28 '22 18:09

gview


Here's a fix:

//Validate Function
function validate($regex,$index,$message) {
    global $errors;
    if(0 === preg_match($regex,$_POST[$index])) {
        $errors[$index] = $message;
    }
}

Here's the issue:

if(0 === preg_match($regex,$_POST[$index],$message)

$message, a string, is where an array of matches is supposed to go. You don't need it.

From the manual: int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

http://php.net/manual/en/function.preg-match.php

like image 38
Brian Duncan Avatar answered Sep 28 '22 16:09

Brian Duncan