Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb
"Accelerated DOM Scripting with Ajax, APIs, and Libraries"
Listing 7-2. simple-form-tidier-js.php adds JavaScript regular expression validation to
simple-form.php
$VALIDATIONS = Array(
"firstname" => Array("regexp" => '.+', "error" => "Enter a name"),
"lastname" => Array("regexp" => '.+', "error" => "Enter a name"),
"heads" => Array("regexp" => '^\d+$',
"error" => "Number of heads should be a whole number"),
"dob" => Array("regexp" => '^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$',
"error" => "Enter dates in format DD/MM/YYYY"),
"email" => Array("regexp" => '^.+@.+\..+$',
"error" => "This address is not valid")
);
CHAPTER 7 n FORM VALIDATION AND JAVASCRIPT 152
$ERRORS = Array();
if (isset($_GET["submit"])) {
# form was submitted
foreach ($VALIDATIONS as $field => $data) {
if (!isset($_GET[$field])) continue; # skip any that aren't sent
$regexpstr = $data["regexp"];
if (preg_match("/$regexpstr/", $_GET[$field]) == 0) {
$ERRORS[$field] = $data["error"];
}
}
if (count($ERRORS) == 0) echo "Data OK; now redirect!";
}
?>
"http://www.w3.org/TR/html4/strict.dtd">
A simple PHP form using regular expressions for validation