Making Error Messages Not Display First Time

  • (2 Pages)
  • +
  • 1
  • 2

29 Replies - 4113 Views - Last Post: 06 September 2012 - 12:59 AM Rate Topic: -----

#1 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Making Error Messages Not Display First Time

Posted 05 January 2011 - 09:54 PM

I'm very new to PHP and I'm working on a simple form validation using PHP and Javascript. Everything seems to be working fine in my code except that the first time the page is loaded my error messages saying that I have left a field blank or whatever are shown. Now obviously they are going to be empty the first time because you haven't given the user a chance to enter anything.

I know why this is happening and even on what line of code it is, but I can't come up with a way around it.

Here's my whole code:
<?php // Recive the posted form and present the form again to visitor if validation fails

// Start with the PHP code

$forename = $surname = $username = $password = $age = $email = "";

if(isset($_POST['forename']))// check if $_POST['forname'] has been set from a form yet, if so fix it and set it equal to $forename
	$forename = fix_string($_POST['forename']);
if(isset($_POST['surname']))
	$surname = fix_string($_POST['surname']);
if(isset($_POST['username']))
	$username = fix_string($_POST['username']);
if(isset($_POST['password']))
	$password = fix_string($_POST['password']);
if(isset($_POST['age']))
	$age = fix_string($_POST['age']);
if(isset($_POST['email']))
	$email = fix_string($_POST['email']);

$fail = validate_forename($forename);// call function to validate the forename from $_POST. If it's validated return empty string, if not return error message
$fail .= validate_surname($surname);// add on to the error message if one exists...
$fail .= validate_username($username);
$fail .= validate_password($password);
$fail .= validate_age($age);
$fail .= validate_email($email);

echo "<html><head><title>An Example Form</title>";

if($fail == "")// if there were no errors
{
	// print out what was entered into all the fields
	echo "<body>Form data successfully validated: $forename, $surname, $username, $password, $age, $email.</body>";//------!took out </head in front and </html>
	
	// This is where you would enter posted fields into a database
	
	exit;
}

// Now output the HTML and Javascript code

echo <<<_END

<!-- The HTML Section -->

<style>.signup {border: 1px solid #999999;
		font: normal 14px helvetica; color #444444; } </style>
	
	<script>//Javascript validation methods called here
	/*
	Each call to a function in the validate function will return an empty string
	if the field validates, or an error message if it fails. If there are any errors it
	will not return true and an alert will pop up displaying the errors
	*/
	function validate(form)
	{
		fail = validateForename(form.forename.value)
		fail += validateSurname(form.surname.value)
		fail += validateUsername(form.username.value)
		fail += validatePassword(form.password.value)
		fail += validateAge(form.age.value)
		fail += validateEmail(form.email.value)
		
		if(fail == "") return true// if it returns true the form will be allowed to be submitted
		else
		{
			alert(fail)
			return false// if it returns false an alert pops up and the user can make changes after closing out
		}
	}
	</script></head><body>
	
	<table class="signup" border="0" cellpadding="2"
		cellspacing="5" bgcolor="eeeeee">
	<th colspan="2" align="center">Signup Form</th>
	
	<tr><td colspan="2">Sorry the following errors were found<br />
	in your form: <p><font color=red size=1><i>$fail</i></font></p></td></tr>
	
	<form method="post" action="adduser.php"
		onsubmit="return validate(this)"><!-- call this function when the form is submitted if true, the form can be submitted-->
	<tr><td>Forename</td><td><input type="text" maxlength="32"
		name="forename" value="$forename" /></td></tr>
	<tr><td>Surname</td><td><input type="text" maxlength="32"
		name="surname" value="$surname" /></td></tr>
	<tr><td>Username</td><td><input type="text" maxlength="32"
		name="username" value="$username" /></td></tr>
	<tr><td>Password</td><td><input type="text" maxlength="32"
		name="password" value="$password" /></td></tr>
	<tr><td>Age</td><td><input type="text" maxlength="32"
		name="age" value="$age" /></td></tr>
	<tr><td>Email</td><td><input type="text" maxlength="32"
		name="email" value="$email" /></td></tr>
	<tr><td colspan="2" align="center">
		<input type="submit" value="Signup" /></td></tr></form></table>
		
	<!-- The Javascript section -->
	
	<script type="text/javascript">
	function validateForename(field)
	{
		if(field == "") return "No Forename was entered.\n"// not entering anything is an error, return an error message
		return ""// else return empty string
	}
	
	function validateSurname(field)
	{
		if(field == "") return "No Surname was entered.\n"// not entering anything is an error, return an error message
		return ""// else return empty string
	}
	
	function validateUsername(field)
	{
		if(field == "") return "No Username was entered.\n"// not entering anything is an error, return an error message
		else if(field.length < 5)// if the length of the entered username is less than 5 characters it's an error, return error message
		{
			return "Usernames must be at least 5 characters.\n"
		}
		else if(/[^a-zA-Z0-9_-]/.test(field))// regular expression to check if there is anything else besides a-Z,A-Z,0-9,_ and -. If so, error
		{
			return "Only a-z, A-Z, 0-9 - and _ allowed in Usernames.\n"
		}
		return ""// if nothing wrong with entered username, return empty string
	}
	
	function validatePassword(field)
	{
		if(field == "") return "No Password was entered.\n"// not entering anything is an error, return an error message
		else if(field.length < 6)// if the length of the entered password is less than 6 characters it's an error, return error message
		{
			return "Passwords must be at least 6 characters.\n"
		}
		else if(!(/[a-z]/.test(field) && /[A-Z]/.test(field) && /[0-9]/.test(field)))//regular expression to check if password contains at least one of each, if not it's an error
		{	
			return "Passwords require one of each of a-z, A-Z, and 0-9.\n"
		}
		return ""// if nothing wrong with entered password, return empty string
	}
	
	function validateAge(field)
	{
		if(isNaN(field)) return "No Age was entered.\n"// not entering a number is an error, return an error message
		else if(field < 18 || field > 110)// entering an age under 18 or greater than 110 is an error, return error message
		{
			return "Age must be between 18 and 110.\n"
		}
		return ""// if nothing wrong with entered age, return empty string
	}
	
	function validateEmail(field)
	{
		if(field == "") return "No Email was entered.\n"// not entering anything is an error, return an error message
		else if(!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) && /[\W]/.test(field))// if . and @ are first letter or not there at all or if doesn't contain the stuff, it's an error
		{
			return "The email address is invalid.\n"
		}
		return ""// if nothing wrong with entered password, return empty string
	}
	</script></body></html>
_END;

// Now implement the PHP functions

function validate_forename($field)
{
	if($field == "") return "No Forename was enetered<br />";
	return "";
}

function validate_surname($field)
{
	if($field == "") return "No Surname was entered<br />";
	return "";
}

function validate_username($field)
{
	if($field == "") return "No Username was entered<br />";
	else if(strlen($field) < 5)
	{
		return "Usernames must be at least 5 characters<br />";
	}
	else if(preg_match("/[^a-zA-Z0-9_-]/", $field))
	{
		return "Only letters, numbers, - and _ in usernames<br />";
	}
	return "";
}

function validate_password($field)
{
	if($field == "") return "No Password was entered<br />";
	else if(strlen($field) < 6)
	{
		return "Passwords must be at atleast 6 characters<br />";
	}
	else if(!preg_match("/[a-z]/", $field) ||
			!preg_match("/[A-Z]/", $field) ||
			!preg_match("/[0-9]/", $field))
			{
				return "Passwords require 1 of each of a-z, A-Z, and 0-9<br /";
			}
	return "";
}

function validate_age($field)
{
	if($field == "") return "No Age was entered<br />";
	else if($field < 18 || $field > 110)
	{
		return "Age must be between 18 and 110<br />";
	}
	return "";
}

function validate_email($field)
{
	if($field == "") return "No Email was entered<br />";
	else if(!((strpos($field, ".") > 0) &&
			  (strpos($field, "@") > 0)) ||
			  preg_match("/[^a-zA-Z0-9.@_-]/", $field))
			  {
				return "The Email address is invalid<br />";
			  }
	return "";
}

// Function to sanitize each field and prevent code injection
function fix_string($string)
{
	if(get_magic_quotes_gpc()) $string = stripslashes($string);
	return htmlentities($string);
}

?>



This is where the problem is occurring specifically:

First time through these will all come out with error messages because the variables have not been set with the $_POST array yet:
$fail = validate_forename($forename);// call function to validate the forename from $_POST. If it's validated return empty string, if not return error message
$fail .= validate_surname($surname);// add on to the error message if one exists...
$fail .= validate_username($username);
$fail .= validate_password($password);
$fail .= validate_age($age);
$fail .= validate_email($email);



And then since those have the error messages, this is called in the HTML section:
<tr><td colspan="2">Sorry the following errors were found<br />
	in your form: <p><font color=red size=1><i>$fail</i></font></p></td></tr>



I'm sure this is an easy fix, but I've been thinking about it for a little while now and can't figure out a way around it.

Thanks for the help!

Is This A Good Question/Topic? 0
  • +

Replies To: Making Error Messages Not Display First Time

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,050
  • Joined: 15-July 08

Re: Making Error Messages Not Display First Time

Posted 05 January 2011 - 10:01 PM

In situations like this, I usually write a function that reads the $_POST array to make sure that all variables are set and the values are not empty. This can be done with a simple for loop ($_POST is an associative array). If this function returns false, I leave a message and call exit.
Was This Post Helpful? 2
  • +
  • -

#3 stevo86  Icon User is offline

  • New D.I.C Head

Reputation: 13
  • View blog
  • Posts: 33
  • Joined: 05-January 11

Re: Making Error Messages Not Display First Time

Posted 05 January 2011 - 10:04 PM

You could add a simple check to verify that the post has been submitted before running the PHP error checks.

if (isset($_POST['submit']))
{
  $fail = validate_forename($forename);
  // etc...
}



This way you don't get any error messages showing up until after the user hits the submit button for the first time.

This post has been edited by stevo86: 05 January 2011 - 10:04 PM

Was This Post Helpful? 2
  • +
  • -

#4 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Making Error Messages Not Display First Time

Posted 05 January 2011 - 10:38 PM

Thanks guys. I've decided to try stevo's approach on this one. Here are the changes I've made:

if(isset($_POST['submit']))
{
$fail = validate_forename($forename);// call function to validate the forename from $_POST. If it's validated return empty string, if not return error message
$fail .= validate_surname($surname);// add on to the error message if one exists...
$fail .= validate_username($username);
$fail .= validate_password($password);
$fail .= validate_age($age);
$fail .= validate_email($email);
}

echo "<html><head><title>An Example Form</title>";

if($fail == "" && isset($_POST['submit']))// if there were no errors
{
	// print out what was entered into all the fields
	echo "<body>Form data successfully validated: $forename, $surname, $username, $password, $age, $email.</body>";//------!took out </head in front and </html>
	
	// This is where you would enter posted fields into a database
	
	exit;
}



Something is going very wrong now though. Now when I hit signup the page gets refreshed but no error messages happen at all. Even if I fill in the form correctly or with errors nothing happens. How did these little changes completely screw it up?


EDIT: Ahh, just figured it out. Forgot I had to add a name to the submit button in order to access it from the $_POST array.

For anyone following along, this is what I had to change:
<input type="submit" name ="submit" value="Signup" /></td></tr></form></table>


This post has been edited by eZACKe: 05 January 2011 - 10:41 PM

Was This Post Helpful? 0
  • +
  • -

#5 stevo86  Icon User is offline

  • New D.I.C Head

Reputation: 13
  • View blog
  • Posts: 33
  • Joined: 05-January 11

Re: Making Error Messages Not Display First Time

Posted 05 January 2011 - 10:42 PM

I may be mistaken but I think you just need to add an </head> tag to display the results. They should be showing in the source either way, if you hit view-source they should show up somewhere in the <head> section. If not, try making your new code like this:


if(isset($_POST['submit']))
{
$fail = validate_forename($forename);// call function to validate the forename from $_POST. If it's validated return empty string, if not return error message
$fail .= validate_surname($surname);// add on to the error message if one exists...
$fail .= validate_username($username);
$fail .= validate_password($password);
$fail .= validate_age($age);
$fail .= validate_email($email);
}

echo "<html><head><title>An Example Form</title>";

if($fail == "" && isset($_POST['submit']))// if there were no errors
{
	// print out what was entered into all the fields
        echo "</head>";
	echo "<body>Form data successfully validated: $forename, $surname, $username, $password, $age, $email.</body>";//------!took out </head in front and </html>
	
	// This is where you would enter posted fields into a database
	
	exit;
}


Was This Post Helpful? 0
  • +
  • -

#6 atik97  Icon User is offline

  • ???
  • member icon

Reputation: 144
  • View blog
  • Posts: 715
  • Joined: 16-September 08

Re: Making Error Messages Not Display First Time

Posted 05 January 2011 - 11:07 PM

Good to know its working, but the issue you might haven't noticed here is the way its written isn't so good. You have mixed html, css, javascript and php code altogether, which is a bad practice. If you need to make a simple change to a logic, you have to go through all the code, similarly any alteration to presentation will need take care of logical part to ensure nothing has broken and its still working. So try to organize the code which will be very helpful in the long run.

This post has been edited by atik97: 05 January 2011 - 11:08 PM

Was This Post Helpful? 0
  • +
  • -

#7 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 07:22 AM

View Postatik97, on 06 January 2011 - 02:07 AM, said:

Good to know its working, but the issue you might haven't noticed here is the way its written isn't so good. You have mixed html, css, javascript and php code altogether, which is a bad practice. If you need to make a simple change to a logic, you have to go through all the code, similarly any alteration to presentation will need take care of logical part to ensure nothing has broken and its still working. So try to organize the code which will be very helpful in the long run.

How exactly do you suggest doing that? Like I said I just started learning PHP and Javascript and I'm only half way through a beginners book. I'm guessing this book most likely wont get into "good practice".
Was This Post Helpful? 0
  • +
  • -

#8 stevo86  Icon User is offline

  • New D.I.C Head

Reputation: 13
  • View blog
  • Posts: 33
  • Joined: 05-January 11

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 07:32 AM

The general approach is to keep everything in separate files. For example, let's say you've got a basic form document:

<?php require_once('functions_forms.php'); ?>
<!doctype html>
<html>
<head>
  <title>My Form</title>
  <link rel="stylesheet" type="text/css" href="style.css" /> <!-- now your style is separate from your markup code -->
  <script type="text/javascript" src="functions_forms.js"></script><!-- and your javascript form validation is separate -->
</head>
<body>
  <div id="container">
  <form method="post" action="process.php"><!-- this keeps PHP processing code separate... -->
  <input type="text" id="whatever" />
  <input type="submit" id="submit" name="submit" value="Submit" />
  </form>
</body>
</html>



So now the HTML code is pretty much, just HTML. If you want to update your content it only takes a few minutes because the only thing in your HTML file is a few lines of markup mixed with straight content.

Then in your CSS file, you've got all the space in the world to style away however you'd like and you know exactly where to look to adjust the visual properties of your elements.

Also, thanks to the <script src=""></script> part, your Javascript functions are all tucked away in their own file so if you decide to modify them, you know exactly where to go and you get straight to the Javascript, as opposed to scrolling through 300 lines of content/HTML that would otherwise hide the Javascript and make it harder to debug.

Lastly, the require_once() PHP function keeps all your PHP neatly tucked away in it's own hiding place and the process.php file is also kept separate so when you want to adjust how the form is processed, the code that does the processing is nicely isolated and easy to read through and modify.

All very simple tricks that make your life easier in the long run. I definitely agree and suggest you take a whack at it at the very least. It may not seem like a big deal on smaller projects, and may even seem counter-productive, but when your projects start getting larger and the code gets longer, it's EXTREMELY nice to be able to have one file for PHP functions, one for Javascript, one for CSS, and one for HTML/content. And even breaking it down further so you have one for PHP form validation functions, one for PHP database functions, etc. Same with the Javascript files. It's all about organization and it really does save time and headaches down the road.

This post has been edited by stevo86: 06 January 2011 - 07:34 AM

Was This Post Helpful? 1
  • +
  • -

#9 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 07:40 AM

Thank you a lot for giving me a nice example of that! I think I'll try to convert this program into something similar to what you suggested.
Was This Post Helpful? 0
  • +
  • -

#10 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 08:00 AM

A quick question for you stevo: The basic form document you've posted, is that a .html document? I wasn't aware that you could put php directly into html without it being a .php file?
Was This Post Helpful? 0
  • +
  • -

#11 stevo86  Icon User is offline

  • New D.I.C Head

Reputation: 13
  • View blog
  • Posts: 33
  • Joined: 05-January 11

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 08:16 AM

View PosteZACKe, on 06 January 2011 - 02:00 PM, said:

A quick question for you stevo: The basic form document you've posted, is that a .html document? I wasn't aware that you could put php directly into html without it being a .php file?


No, I meant it to be a .php file. I only use .php files as of late. Though I'm fairly certain you can use a .htaccess rewrite rule to make them all appear as .html files or to force the PHP interpreter to process .html files. I can't remember which way it worked, but it is possible to end up with index.html or whatever.html even if you do have PHP code in there, and it will get processed.
Was This Post Helpful? 0
  • +
  • -

#12 atik97  Icon User is offline

  • ???
  • member icon

Reputation: 144
  • View blog
  • Posts: 715
  • Joined: 16-September 08

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 09:17 AM

You can still parse php code from a file with .html extension (or other extensions) by simply adding that extension to the apache configuration file httpd.conf -

AddType application/x-httpd-php .php



just include .html or other extension in the previous line followed by a space -

AddType application/x-httpd-php .php .html



But remember, there might be a performance issue there, as every html file will be passed to php parser.
Was This Post Helpful? 1
  • +
  • -

#13 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 10:34 AM

Okay I think I might be getting a little lost in trying to separate these into a more organized program.

I've turned the one long program into 5 smaller ones:
  • phpHTMLTest.php -- Used for displaying a form and a table
  • style.css -- Used for my CSS code
  • functions.php -- All of my PHP functions are in there
  • functions.js -- All of my Javascript functions are in there
  • process.php -- All of my code that handles processing the form is in there


phpHTMLTest.php is my main page or I guess you'd call my "index".

Many things do wrong when I run this:
  • When I hit submit only the Javascript code seems to be running. An alert message comes up, which isn't really suppose to come up. It didn't when I had it all in the one program called adduser.php from my original post. The $fail message is not being displayed at all.
  • I put a debugging echo statement at the top of process.php and it gets called as soon as the phpHTMLTest.php is run. It doesn't even wait for the signup button to be pressed. It doesn't seem to get called at all after pressing signup though if errors are found when validating (I think the validation that occurs is the Javascript validation, not the PHP because as far as I can tell process.php is not called).


Here's my code:

phpHTMLTest.php
<?php
require_once('functions.php');
require_once('process.php');
?>

<html>
	<head><title>A Quick Test</title></head><body>
	<link rel="stylesheet" type="text/css" href="style.css" /><!--Should handle the CSS-->
	<script type="text/javascript" src="functions.js"></script><!--Should handle the Javascript-->
	
	<table class="signup" border="0" cellpadding="2"
		cellspacing="5" bgcolor="eeeeee">
	<th colspan="2" align="center">Signup Form</th>
	
	<tr><td colspan="2">Sorry the following errors were found<br />
	in your form: <p><font color=red size=1><i><?php echo $fail?></i></font></p></td></tr>
	
	<form method="post" action="process.php"
		onsubmit="return validate(this)"><!-- call this function when the form is submitted if true, the form can be submitted-->
	<tr><td>Forename</td><td><input type="text" maxlength="32"
		name="forename" value="<?php echo $forename?>" /></td></tr>
	<tr><td>Surname</td><td><input type="text" maxlength="32"
		name="surname" value="<?php echo $surname?>" /></td></tr>
	<tr><td>Username</td><td><input type="text" maxlength="32"
		name="username" value="<?php echo $username?>" /></td></tr>
	<tr><td>Password</td><td><input type="password" maxlength="32"
		name="password" value="<? echo $password?>" /></td></tr>
	<tr><td>Age</td><td><input type="text" maxlength="32"
		name="age" value="<?php echo $age?>" /></td></tr>
	<tr><td>Email</td><td><input type="text" maxlength="32"
		name="email" value="<?php echo $email?>" /></td></tr>
	<tr><td colspan="2" align="center">
		<input type="submit" name ="submit" value="Signup" /></td></tr></form></table></body>
</html>



style.css
.signup {border: 1px solid #999999;
		font: normal 14px helvetica; color #444444; }



fuctions.php
<?php 
function validate_forename($field)
{
	if($field == "") return "No Forename was enetered<br />";
	return "";
}

function validate_surname($field)
{
	if($field == "") return "No Surname was entered<br />";
	return "";
}

function validate_username($field)
{
	if($field == "") return "No Username was entered<br />";
	else if(strlen($field) < 5)
	{
		return "Usernames must be at least 5 characters<br />";
	}
	else if(preg_match("/[^a-zA-Z0-9_-]/", $field))
	{
		return "Only letters, numbers, - and _ in usernames<br />";
	}
	return "";
}

function validate_password($field)
{
	if($field == "") return "No Password was entered<br />";
	else if(strlen($field) < 6)
	{
		return "Passwords must be at atleast 6 characters<br />";
	}
	else if(!preg_match("/[a-z]/", $field) ||
			!preg_match("/[A-Z]/", $field) ||
			!preg_match("/[0-9]/", $field))
			{
				return "Passwords require 1 of each of a-z, A-Z, and 0-9<br /";
			}
	return "";
}

function validate_age($field)
{
	if($field == "") return "No Age was entered<br />";
	else if($field < 18 || $field > 110)
	{
		return "Age must be between 18 and 110<br />";
	}
	return "";
}

function validate_email($field)
{
	if($field == "") return "No Email was entered<br />";
	else if(!((strpos($field, ".") > 0) &&
			  (strpos($field, "@") > 0)) ||
			  preg_match("/[^a-zA-Z0-9.@_-]/", $field))
			  {
				return "The Email address is invalid<br />";
			  }
	return "";
}

// Function to sanitize each field and prevent code injection
function fix_string($string)
{
	if(get_magic_quotes_gpc()) $string = stripslashes($string);
	return htmlentities($string);
}
?>



functions.js
	function validate(form)
	{
		fail = validateForename(form.forename.value)
		fail += validateSurname(form.surname.value)
		fail += validateUsername(form.username.value)
		fail += validatePassword(form.password.value)
		fail += validateAge(form.age.value)
		fail += validateEmail(form.email.value)
		
		if(fail == "") return true// if it returns true the form will be allowed to be submitted
		else
		{
			alert(fail)
			return false// if it returns false an alert pops up and the user can make changes after closing out
		}
	}
	
	function validateForename(field)
	{
		if(field == "") return "No Forename was entered.\n"// not entering anything is an error, return an error message
		return ""// else return empty string
	}
	
	function validateSurname(field)
	{
		if(field == "") return "No Surname was entered.\n"// not entering anything is an error, return an error message
		return ""// else return empty string
	}
	
	function validateUsername(field)
	{
		if(field == "") return "No Username was entered.\n"// not entering anything is an error, return an error message
		else if(field.length < 5)// if the length of the entered username is less than 5 characters it's an error, return error message
		{
			return "Usernames must be at least 5 characters.\n"
		}
		else if(/[^a-zA-Z0-9_-]/.test(field))// regular expression to check if there is anything else besides a-Z,A-Z,0-9,_ and -. If so, error
		{
			return "Only a-z, A-Z, 0-9 - and _ allowed in Usernames.\n"
		}
		return ""// if nothing wrong with entered username, return empty string
	}
	
	function validatePassword(field)
	{
		if(field == "") return "No Password was entered.\n"// not entering anything is an error, return an error message
		else if(field.length < 6)// if the length of the entered password is less than 6 characters it's an error, return error message
		{
			return "Passwords must be at least 6 characters.\n"
		}
		else if(!(/[a-z]/.test(field) && /[A-Z]/.test(field) && /[0-9]/.test(field)))//regular expression to check if password contains at least one of each, if not it's an error
		{	
			return "Passwords require one of each of a-z, A-Z, and 0-9.\n"
		}
		return ""// if nothing wrong with entered password, return empty string
	}
	
	function validateAge(field)
	{
		if(isNaN(field)) return "No Age was entered.\n"// not entering a number is an error, return an error message
		else if(field < 18 || field > 110)// entering an age under 18 or greater than 110 is an error, return error message
		{
			return "Age must be between 18 and 110.\n"
		}
		return ""// if nothing wrong with entered age, return empty string
	}
	
	function validateEmail(field)
	{
		if(field == "") return "No Email was entered.\n"// not entering anything is an error, return an error message
		else if(!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) && /[\W]/.test(field))// if . and @ are first letter or not there at all or if doesn't contain the stuff, it's an error
		{
			return "The email address is invalid.\n"
		}
		return ""// if nothing wrong with entered password, return empty string
	}



process.php
<?php
require_once('functions.php');
$forename = $surname = $username = $password = $age = $email = "";

if(isset($_POST['forename']))// check if $_POST['forname'] has been set from a form yet, if so fix it and set it equal to $forename
	$forename = fix_string($_POST['forename']);
if(isset($_POST['surname']))
	$surname = fix_string($_POST['surname']);
if(isset($_POST['username']))
	$username = fix_string($_POST['username']);
if(isset($_POST['password']))
	$password = fix_string($_POST['password']);
if(isset($_POST['age']))
	$age = fix_string($_POST['age']);
if(isset($_POST['email']))
	$email = fix_string($_POST['email']);

if(isset($_POST['submit']))// only do this if submit has been pressed, thus error messages will not show before hitting signup for first time
{
	$fail = validate_forename($forename);// call function to validate the forename from $_POST. If it's validated return empty string, if not return error message
	$fail .= validate_surname($surname);// add on to the error message if one exists...
	$fail .= validate_username($username);
	$fail .= validate_password($password);
	$fail .= validate_age($age);
	$fail .= validate_email($email);
}

if($fail == "" && isset($_POST['submit']))// if there were no errors after signup for the first time
{
	// print out what was entered into all the fields
	echo "<body>Form data successfully validated: $forename, $surname, $username, $password, $age, $email.</body>";
	
	// This is where you would enter posted fields into a database
	
	exit;
}
?>





EDIT: Been working on it for a while now. Fixed almost all of my problems, but still have a couple which are the ones that remain in the list above.

Thanks for the help!

This post has been edited by eZACKe: 06 January 2011 - 01:49 PM

Was This Post Helpful? 0
  • +
  • -

#14 stevo86  Icon User is offline

  • New D.I.C Head

Reputation: 13
  • View blog
  • Posts: 33
  • Joined: 05-January 11

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 02:13 PM

Sorry to leave you hanging, I finally crashed after just about 62 hours of no sleep.

Firstly, process.php doesn't need to be a require_once(), you only need to put that in the action="process.php" part.

Secondly, and this may or may not even be causing any of your problems, but I would add semi-colons to the end of your statements in "functions.js". It makes things a bit clearer to read through and a bit more uniform since you have to do it for PHP anyways.

Third, one small discrepancy I noticed is that in your PHP version of validate_password you have a function that verifies that at least one lower case, one upper case or one number were used, however in the javascript you required at least one lower case, one upper case, AND one number. You used || in the PHP and && in Javascript basically, which will result in different actions.
Was This Post Helpful? 0
  • +
  • -

#15 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Making Error Messages Not Display First Time

Posted 06 January 2011 - 04:02 PM

I don't need to require_once process.php? The how will phpHTMLTest.php have access to $fail here:
<tr><td colspan="2">Sorry the following errors were found<br />
	in your form: <p><font color=red size=1><i><?php echo $fail?></i></font></p></td></tr>



I have added the semicolons.

And thanks for picking up that last one. That was just me going to fast for my own good.

Anyway, now that I've done that this is what is happening:
  • The $fail is still not being displayed at all
  • When I press signup with errors it just shows the javascript alert
  • When no errors are entered and I press signup it works correctly

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2