Solved

Display errors on form submission

Posted on 2011-09-22
5
163 Views
Last Modified: 2012-05-12
On this page http://bit.ly/nVz4fr I am trying to get my error messages to display if the fields are blank or not correct. Right now they're displaying up top on page load and not on submit. My code is attached.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Bowling Exercise</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
label
{
	width: 4em;
	float: left;
	text-align: right;
	margin-right: 0.5em;
	display: block
}

.submit input
{
	margin-left: 4.5em;
} 
input
{
	color: #781351;
	background: #fee3ad;
	border: 1px solid #781351
}

.submit input
{
	color: #000;
	background: #ffa20f;
	border: 2px outset #d7b9c9
} 
fieldset
{
	border: 1px solid #781351;
	width: 20em
}

legend
{
	color: #fff;
	background: #ffa20c;
	border: 1px solid #781351;
	padding: 2px 6px
} 

</style>
</head>

<body>

<?php

$Dir = "Project";
if (is_dir($Dir)) {
	if (isset($_POST['save'])) {
		if (empty($_POST['name']))
		$SaveString = "New Bowler\n\r";
		else
		$SaveString = stripslashes($_POST['fname']) . ",";
		$SaveString .= stripslashes($_POST['lname']) . ",";
		$SaveString .= stripslashes($_POST['fname']) . ",";
		$SaveString .= stripslashes($_POST['age']) . ",";
		$SaveString .= stripslashes($_POST['average']) . "\n\r";
		$SaveString .= date('r') . "\n";
		$CurrentTime = microtime();
		$TimeArray = explode(" ", $CurrentTime);
		$TimeStamp = (float)$TimeArray[1] + (float)$TimeArray[0];
		/* File name is " bowler.seconds.microseconds.txt" */
		
		$SaveFileName= "$Dir/bowler.$TimeStamp.txt";
		if (file_put_contents($SaveFileName, $SaveString)>0)
		echo "File \"" . htmlentities($SaveFileName) . "\" successfully saved.<br />\n\r";
		else
		echo "There was an error writing \"" . htmlentities($SaveFileName) . "\".<br />\n\r";
	}
}


?>


<?php
$Number = "";
$First = "";
$Last = "";
$Age = "";

if (isset($_POST['Submit'])) {
	$Number = $_REQUEST['average'];
	if (is_numeric($Number)) {
	}else {
		echo "<p>You need to enter a numeric value.</p>\n";
	}
}


if (empty($Number)) {
	$Number = $_REQUEST['average'];
	echo "Please enter a number.";
}

if (empty($First) ) {
	$First = $_REQUEST['fname'];
	echo "Please enter your first name.";
}

if (empty($Last)) {
	$Last = $_REQUEST['lname'];
	echo "Please enter your last name.";
}

if (empty($Number)) {
	$Number = $_REQUEST['average'];
	echo "Please enter your average.";
}
if (empty($Age) ) {
	$Age = $_REQUEST['age'];
	echo "Please enter your age.";
}

if (empty($Age)) {
	$Age = $_REQUEST['age'];
	echo "Please enter a number.";
}
?>


<h2 style="color:#06C">Bowler Stats</h2>
<form action="bowling.php" method="post">
<fieldset>
<legend>Bowler Registration</legend>
<p> <label for="First:">First: </label> <input type="text" name="fname" /></p>
<p> <label for="Last:">Last: </label> <input type="text" name="lname" /></p>
<p><label for="Age:">Age:</label> <input type="text" name="age" /><br />
<p><label for="Average:">Average:</label> <input type="text" name="average" /><br />
<p class="submit"><input type="submit" name="save" value="Register" style="width: 100px"  /></p>

</fieldset>
</form>


</body>

</html>

Open in new window

0
Comment
  • 2
  • 2
5 Comments
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 36585050
You need to check the validation on after submission process

after,

if (isset($_POST['save'])) {
                if (empty($_POST['name']))
0
 
LVL 1

Author Comment

by:catonthecouchproductions
ID: 36585069
Can you elaborate a little bit?
0
 
LVL 36

Accepted Solution

by:
Loganathan Natarajan earned 500 total points
ID: 36585114

$Dir = "Project";
if (is_dir($Dir)) {
        if (isset($_POST['save'])) {
                if (empty($_POST['name']))
                $SaveString = "New Bowler\n\r";
                else
					//for first name
					if (!isset($_POST['fname'])) {
							die "Please enter a first name.";
					}
					
					if (!isset($_POST['lname'])) {
							die "Please enter a first name.";
					}
					
					if (!isset($_POST['age'])) {
							die "Please enter a first name.";
					}
					
					if (!isset($_POST['average'])) {
							die "Please enter average.";
					}
					
					if (!is_numeric($_POST['average'])) {					
							echo "<p>You need to enter a numeric value.</p>\n";
					}
		
                $SaveString = stripslashes($_POST['fname']) . ",";
                $SaveString .= stripslashes($_POST['lname']) . ",";
                $SaveString .= stripslashes($_POST['fname']) . ",";
                $SaveString .= stripslashes($_POST['age']) . ",";
                $SaveString .= stripslashes($_POST['average']) . "\n\r";
                $SaveString .= date('r') . "\n";
                $CurrentTime = microtime();
                $TimeArray = explode(" ", $CurrentTime);
                $TimeStamp = (float)$TimeArray[1] + (float)$TimeArray[0];
                /* File name is " bowler.seconds.microseconds.txt" */
                
                $SaveFileName= "$Dir/bowler.$TimeStamp.txt";
                if (file_put_contents($SaveFileName, $SaveString)>0)
                echo "File \"" . htmlentities($SaveFileName) . "\" successfully saved.<br />\n\r";
                else
                echo "There was an error writing \"" . htmlentities($SaveFileName) . "\".<br />\n\r";
        }
}

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36590662
This code snippet teaches the design pattern that is usually used for this sort of thing.  You can see the demonstration on my server here.
http://www.laprbass.com/RAY_form_highlight_errors.php
<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// WE TURN THE FORM BORDER RED
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE INITIAL ENTRY
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';
        // $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';
        // $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36592504
Not to put too fine a point on it, but using die() instead of giving the client an opportunity to correct the errors is not a design pattern that would make sense to me.  And the need for stripslashes() would probably be predicated on "magic quotes" which should already be turned off in your server.

Good luck!
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now