PHP form validation function

I am currently writing some PHP form validation (I have already tested clients) and have some repetitive code which I think will work well in a small little PHP function. However, I have problems with his work. I am sure this is just a matter of syntax, but I just can't nail it.

Any help was 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 wrote a lot of verification code, 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 that ...

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

Can anyone understand why this will not work?

Note. I turned off client-side validation while I am working on it to try to cause an error, so the value I send for "Phone" is not valid.

+7
source share
3 answers

Try something more thoughtful.

You want to use it like this:

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

Then I would suggest the following:

 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 the opportunity to reset the validation on error, or you can associate this transfer with $ errors and fill it with validation errors. Globals were not used.

+4
source

Here's the fix:

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

Here's the problem:

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

$message , the line where the match array should be selected. You do not 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

+1
source

You do not have enough closing parentheses if your validation function Change this

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

For this

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

All Articles