Solved

Display errors on form submission

Posted on 2011-09-22
5
166 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 109

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 109

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Wordpress errors showing up, hacked? 4 37
Why do people dis php? 5 54
UPDATE query not working in mysqli php 8 52
How can I make this form submit to itself? 10 28
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

825 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