Form validation

This example shows how to validate form data and to redisplay the form highlighting fields that need to be changed.


<!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/17/2008
-->
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$submit = $_POST["submit"]; // to check if the user got here through a form

function display_form($style1 = "", $style2 = "", $name_value="", 
		      $email_value = "") {
                print "<form  method=\"post\"
                action=\"form_validation.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>";

}
?>
<html  xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<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_spring08/forms/form_validation.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.