I have a form being validated in the following manner:
//Clear all variables
$formCheck = '';
$rep = '';
$name = '';
$department = '';
$location = '';
$email = '';
$phone = '';
$type = '';
$drink = '';
$notes = '';
$lastVisited = '';
$nextVisit = '';
$clean_formCheck = '';
$clean_rep = '';
$clean_name = '';
$clean_department = '';
$clean_location = '';
$clean_email = '';
$clean_phone = '';
$clean_type = '';
$clean_drink = '';
$clean_notes = '';
$clean_lastVisited = '';
$clean_nextVisit = '';
function validateRep($rep){
...some code...
}
$formCheck = $_POST["formCheck"];
$rep = $_POST["rep"];
$name = $_POST["name"];
$department = $_POST["department"];
$location = $_POST["location"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$type = $_POST["type"];
$drink = $_POST["drink"];
$notes = $_POST["notes"];
$lastVisited = $_POST["lastVisited"];
$nextVisit = $_POST["nextVisit"];
if (validateRep($rep)){
$clean_rep = $rep;
}else{
echo "Invalid Rep";
exit();
}
//.....and so on......
I was wondering if it would be more efficient / cleaner to validate using an an array instead of individual variable? If so, how would I go about that, and how would I write the different validation functions all in one (eg. right now I have a separate function to validate each field), would it be possible with a loop through the array? i was experimenting and so far this is what I have:
$unclean['formCheck'] = $_POST["formCheck"];
$unclean['rep'] = $_POST["rep"];
$unclean['name'] = $_POST["name"];
$unclean['department'] = $_POST["department"];
$unclean['location'] = $_POST["location"];
$unclean['email'] = $_POST["email"];
$unclean['phone'] = $_POST["phone"];
$unclean['type'] = $_POST["type"];
$unclean['drink'] = $_POST["drink"];
$unclean['notes'] = $_POST["notes"];
$unclean['lastVisited'] = $_POST["lastVisited"];
$unclean['nextVisit'] = $_POST["nextVisit"];
$clean = array(
'rep', 'name', 'department', 'location', 'email', 'phone', 'type', 'drink', 'lastVisited', 'nextVisit',
);
but I’m not sure how to proceed from here.
I would use something along these lines… Just coded this very quickly, basically you create validation functions that match the post fields and return true or false if the validation passed. e.g. validate_department, validate_type, validate_drink, etc. Will work if your post data doesn’t have any strange characters in (which so far it doesn’t)
And the validate class… Use $errorMsg to see the error messages should you run into any issues