PHP form validation function

Posted by Barbs on Stack Overflow See other posts from Stack Overflow or by Barbs
Published on 2012-12-19T05:02:02Z Indexed on 2012/12/19 5:02 UTC
Read the original article Hit count: 104

Filed under:
|
|
|

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 have 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],$message) {
        $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.

© Stack Overflow or respective owner

Related posts about php

Related posts about regex