PHP form validation function
function, php, regex, validation
Solution
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.
Problem
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.