Validating form data

Validating form data and displaying errors so that the user can resubmit

<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Displaying error messages for forms
Author: Elena Machkasova
Last Modifed: 4/13/2006
-->
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$submit = $_POST["submit"]; // check if the user got here through a form

function display_form($style1 = "", $style2 = "", $name_value="", 
		      $email_value = "") {
                print "<form  method=\"post\"
                action=\"error_messages.php\">
                <table style=\"border: none\">
                <tr>
                <td $style1>Enter your name:</td>
                <td>
                <input type = \"text\" name = \"name\" $name_value>
                </td>
                </tr>
                <tr>
                <td $style2>Enter your e-mail:</td>
                <td>
                <input type = \"text\" name = \"email\" $email_value>
                </td>
                </tr>
                <tr>
                <td>
                <input type=\"submit\" name = \"submit\" value=\"submit\">
                </td>
                </tr>
                </table>
                </form><br/>";

}
?>
<html>
<head>
<title>
Displaying errors
</title>
</head>
<body>
<?php

$style1 = "";
$style2 = "";
$error_style = "style = \"color: red\"";
$message = "";
$name_value = "";
$email_value = "";
$errors = false;

if (!isset($submit)) {
  display_form(); // display the form
}
else {
	// start validation
	if (!eregi("^[a-z ]+$", $name)) {
		$style1 = $error_style;
		$message = $message."The name is empty or has illegal characters<br/>";
		$errors = true;
	} else {
		$name_value = "value = \"$name\"";	
	}
	if (!eregi("^([a-z0-9]+)@([a-z._]+)$", $email)) {
		$style2 = $error_style;
		$message = $message."The e-mail is empty or has illegal characters<br/>";
		$errors = true;
	} else {
		$email_value = "value = \"$email\"";	
	}
	if (!$errors) {
		print "Thank you, $name, for submitting your information!<br/>\n";
	} else {
		// priniting the form
	  display_form($style1, $style2, $name_value, $email_value);
	  // printing the error message
	  print "<p $error_style>$message You need to resubmit the form</p>";
	}
}
?>
</body>
</html>
http://rynite.morris.umn.edu/~elenam/1101_spring07/regexp/error_messages.php
UMM CSci 1101

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.