My experiece so far says if you have more than 4-5 validations for the same goal, you are most probably doing something wrong. For validating user input, you might need certain pattern of chars, which you could achieve with regex, you might need all fields to be populated, some exotic things like the user to be from certain country IP or to have checked at least 18 years old in a dropdown. All other things, either beolng to the group of these, or chances are - they are redundant.
As the others stated, you, also, should not nest the blocks, but return the execution if the conditions are not met.
For example:
function isFormPopulated() {
$requiredFields = array('user', 'pass', 'age', 'sex');
foreach ($requiredFields as $field) {
if (empty($_POST[$field])) {
$_SESSION['msg'] = $field . ' field should be populated'; // here better throw exception, instead of session saving the message
return false;
}
}
return true;
}
function isPatternValid() {
$fieldPatterns = array('user' => '/w+/', 'pass' => 'someOtherRegex')
foreach ($fieldPatterns as $field => $pattern) {
if (!preg_match($pattern, $_POST[$field])) {
return false;
}
}
return true;
}
function isUserAllowed() {
if (in_array($_SERVER['REMOTE_ADDR']......) {
return false;
}
return true;
}
function isUserLegal() {
if ($_POST['age'] < self::MIN_ALLOWED_AGE) {
return false;
}
return true;
}
function isValid() {
// here you can check with && the evaluation of the previous functions
// or you can check one by one and return false aswell
// return true at the end
}
function register() {
if (!isValid()) {
return false;
}
// continue execution of the registration process
}
Validating a user input is in most of the cases not coupled on each condition. E.g. a regex condition is not coupled to the legal condition. However, if by design (which I assume wrong) you have coupling. you can chain validation like
function validationFour() {
if (!validationThree() || !current_validation) {
return false;
}
return true;
}
function validationThree() {
if (!validationTwo() || !current_validation) {
return false;
}
return true;
}