7

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.

3
  • I believe that you would need curly braces for php to evaluate the variable index if contained between single quotes. Like so, $_POST['{$index}'] Commented Dec 19, 2012 at 5:10
  • 1
    @Matt: that's not needed. If the param is a string, it will work just fine with $_POST[$index] Commented Dec 19, 2012 at 5:12
  • 1
    There are lots of reasons this doesn't work, not the least of which is your example doesn't make any sense. If this is a function, then you would want to return a value, which you don't. If you also want to set an array to the error message value, then that parameter has to be passed into the function by reference. Commented Dec 19, 2012 at 5:17

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi gview, thanks this looks promising. I want to process the form whenever the $errors array is empty. If the array contains error messages I just want to display the errors to the user for now. If I just check if the validate returns true won't I have to perform this check for every function call? I thought I could check every field that needs validation, then check if the form validated as a group (by simply checking the $errors array) before going to the database. Or am I misunderstanding something?
1

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

3 Comments

Functionally this does the job, but I'm not a fan of the use of global, even though I understand you are just trying to answer the question based on the original code snippet.
Yup, I'm also not a big fan of using global. But then again I'm also not a big fan of one-size fits all validation functions.
agreed. Also so many options out there (symfony2 validate component, ZF2 Validate class.
0

You are missing a closing parentheses at of your if of your validate function Change this

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

To this

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

1 Comment

thanks. Typo when I reproduced the function here. Fixed up top.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.