PHP Form Validation Tip
While doing the assignment for my CA 282 PHP class today, I came up with a trick to minimize the amount of code that I need to write for the validation rule of each form element. This trick especially best used for validating forms with lots of form fields. The following is the PHP code:
if (isset($_GET['submitted'])) {
$field=”username,password,pwconfirm,fname,lname,address,city,state,zip,email”;
$fieldName=”User Name,Password,Confirm Password,First Name,Last Name,Home Address,City,State,Zip,Email”;
$field = split(“,”,$field);
$fieldNm=split(“,”,$fieldName);
for ($i=0;$i<10;$i++) {
if (empty($_POST[$field[$i]])) {
$errorMsg .= $fieldNm[$i].” is required.<br />”;
$success .= “False”;
}
else {
$success .= “True”;
}
}
if (!strstr($success,”False”)) {
$errorMsg=”The form successfully submitted.”;
}
}
else {
$errorMsg = “”;
}
echo “<div id=”noVal”>”.$errorMsg.”</div>”;
As you can see from the code above, I use split function to convert the combined form field names and the actual name for each form field to arrays. I then used a for loop to loop between form fields to validate the form. This is a simple form. It only checks all the form fields that left blank. You can use continue command inside the for loop for certain form fields that don’t need to be validated. You can also use email validation and password=password_confirm validation inside the for loop. Also note that the noVal id at the end of above code is just used to display the error massages to red color and bold.
There are no posts related to PHP Form Validation Tip.