Form validation - best practice for many fields
Posted: Thu Apr 02, 2009 4:10 pm
What's the best practice for validating form fields before submitting to a database or e-mail? Up til now, I've been checking each field against a validateField function, which makes sure that the field is not empty and doesn't have funky characters. But what if I have 20 form fields? Instinct tells me to forget 20 if statements and use a foreach looping through my $POST array. But is this practice safe? Thanks.
This method works well...but is it the best for many fields?
This method works well...but is it the best for many fields?
Code: Select all
// if form was submitted, send e-mail
if (isset($_GET['action'])&&$_GET['action']=='sendMail'){
include_once "validateField_pf.php";
$ad_name = $_POST['ad_name'];
$ad_co = $_POST['ad_company'];
$ad_phone = $_POST['ad_phone'];
$nameCheck = validateField($ad_name);
$coCheck = validateField($ad_co);
$phoneCheck = validateField($ad_phone);
if ($nameCheck && $coCheck && $phoneCheck){
require("hybMail.php");
$mail_details = array($ad_name, $ad_co, $ad_phone);
sendHybMail(1, $mail_details);
}
else {
if ($nameCheck==FALSE){
echo "<span class='alert'>* Please enter a name.</span><br/>";
}
if ($coCheck==FALSE){
echo "<span class='alert'>* Please enter a company name.</span><br/>";
}
if ($phoneCheck==FALSE){
echo "<span class='alert'>* Please enter a phone number.</span><br/>";
}
}
}