Page 1 of 1

Validating forms with an error message PHP?

Posted: Sun Nov 13, 2011 4:07 pm
by TheDumbNerd
Well I have two documents, one called "test.php" and the other "test2.php". I want to validate my First Name form so that when someone enters something that is not alphabetic, or they leave it black then you get redirected back to test.php with the values that you have entered still in the form but an error message has appeared beside the form.
"test.php"

Code: Select all

<?php
@$fname=$_GET["fname"];
@$fnameerror=$_GET["fnameerror"];

if (isset($fname)==true) 
$fnameerror="*";
else
$fnameerror="Testing";

?>

<form action="test2.php" method="GET">
	<p>
	First Name: <br /> <input type="text" name="fname" value="<?php echo $fname; ?>"/> <br/></input><font color="red"><?php echo $fnameerror; ?></font></p>
	</p>
	<p><input type="submit" value="submit" /> </p>
	</form>

Here's my other document "test2.php"

<html>
<h1>Academic Report Card</h1>
</html>
<?php
@$fname=$_GET["fname"];
@$fnameerror=$_GET["fnameerror"];

if ($fname=="" 
or ctype_alpha($fname)==False or $fnameerror=1)
echo ".$fnameerror." 
; header ("location: test.php?fname=$fname&&fnameerror=$fnameerror"); 
 
if ($fnameerror=0)
		echo "<table border=1>";
		echo 
		"<th> <h2>".$fname." </h2> </th>
		";
	 
		echo "</table>";  
?>

Re: Validating forms with an error message PHP?

Posted: Sun Nov 13, 2011 6:18 pm
by twinedev
Check out the sample file I posted in the following thread (the third code chunk in my post). It allows you to post back to the same file, and handles validation and redisplaying the form with error messages and repopulate the form with what they already entered.

A note is that the code lists all the errors at the top of the form, however, since they are in an array, indexed with the same name as the inputs, you can easily display them with their inputs instead.

viewtopic.php?f=1&t=132752#p664993

-Greg