I have multiple form validation checks around my site so I decided to write them as functions to simplify the process of creating the validation pages, here is a snippet for an understanding of what I'm doing.
// Declare regex variables
$regex_email = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
$regex_password = "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).*$/";
// Declare validation functions
function checkEmail($regex, $email) {
if (!preg_match($regex, $email)) {
$error = "The format of that Email Address is invalid";
$solution = "Please go back and <a href=\"javascript:history.go(-1)\">try again</a>";
}
return array($error, $solution);
}
function checkPassword($regex, $password) {
if (!preg_match($regex, $password)) {
$error = "Your Passwords does not meet our requirements";
$solution = "Please go back and <a href=\"javascript:history.go(-1)\">try again</a>";
}
return array($error, $solution);
}
I was hoping that when I come to validate it I could simply use:
// Values for $email and $password are fetched from `$_POST` before hand...
// Validate form
list ($error, $solution) = checkEmail($regex_email, $email);
list ($error, $solution) = checkPassword($regex_password, $password);
// Display error
echo("Error:<br />".$error."<br />Solution:<br />".$solution."");
But alas, it doesn't work and no errors at all are displayed and I'm having to do error checks after each one like this:
// Validate form
list ($error, $solution) = checkEmail($regex_email, $email);
if (!$error) {
list ($error, $solution) = checkPassword($regex_password, $password);
}
// Display error
echo("Error:<br />".$error."<br />Solution:<br />".$solution."");
I don't mind doing it like this, but when I have say 10+ check*VALUE*
functions being called, each one wrapped in an if statement
within an if statement
and so on, it looks a little messy, I wasn't sure if there was a different approach which would work more like the first way I tried without all the if statement
's.