Separation of Presentation from Validation
You may have noticed in that I made it a point to use comments to define where the "user-defined" and form-validation sections began and ended. As I mentioned previously, one of the goals of the form-validation script is to separate presentation code from validation code. Looking at , you may notice that this script can actually be divided into three separate files: one for the HTML form itself, one for the user-defined validation functionality, and a third for the form-validation script.
For argument's sake, let's assume everything between the form-validation script comment markers is in the file formvalidate.php and the HTML form is in the file htmlform.php. By placing the remainder of the code in a third file with a few includes, you would have something resembling (comments removed for the sake of space):
Listing 5.12. Separating the HTML and Validation Code
<?php
include_once('formvalidate.php');
$method = &$_GET;
if(isset($method['submit'])) { validate_form($method); }
function email_validate($data, $desc) { $regex = "/^[a-z0-9\._-]+@+[a-z0-9\._-]+\.+[a-z]{2,3}$/i"; if(preg_match($regex, $data) != 1) return "The '$desc' field is invalid.";
return true; }
function process_form($data) {
$msg = "The form at {$_SERVER['PHP_SELF']}" . " was submitted with these values: \n\n"; foreach($data as $key=>$val) { $msg .= "$key => $val\n"; } mail("joeuser@somewhere.com", "form submission", $msg);
}
include("htmlform.php");
?>
Tags:
Add more tags...,
|