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.
Barbs
source share