Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Form Validation

Validation means checking data to ensure that it has been entered correctly - after it has already been input.

Our script (person.php) must be smart to know when a user has not entered some or all values.

An if fuction can provide basic validation. Let's check our previous script and add some form of validation.

<HTML><HEAD><TITLE>Thank you </TITLE></HEAD><BODY>
<H2>Thank you</H2>
<?php
	if(($username=="") || ($usermail=="") || $Mstatus=="")){ 
		print "<P><font color=\"red\">Unfortunately there is a problem.".
	      	      "  The following fields are blank:";
		
		if($username==""){
		  print "<BR>user Name";
		}
		
		if($usermail =""){
		  print "<BR> Email Address";
		}
		
		if($Mstatus ==""){
		  print "<BR> Marital Status";
		}
	} else {
		print "Thank you <B> $username</B> for your submission. ".
	      	  "Your submission indicates that you are $Mstatus and".
		  " your email address is <B>$username</B>.";
	}
?>
</body></html>

Our coding is starting to get large. First the program tests to see if there any of three fields that is blank:

if(($username =="") || ($usermail =="") || $Mstatus=""))

Remember || means OR. If any of them is equal to "" (blank), the script prints

"Unfortunately there is a problem. The following fields are blank:"

It then proceeds to test each field separately and print it's name (in English not in HTML) if found to be blank:

if($username == ""){
	print "<BR>User Name";
}
...

Notice how this and the other two if statements following this one are enclosed inside another if. They are said to be nested.

If none of the fields are equal to nothing, then a message previous to the one printed in the previous example is output.

So what's wrong with our validation. It only tests to see if the user had entered anything or not - by checking to see that the name is not equal to nothing. Should the user enter a space or some rubbish like that, then you will talking to "*-e6*/\~@ whose email address is &/.>**!@**&. God! Looks like a cartoon cursing!

Never trust the user to do the right thing. How many times have you tried 'skipping' a HTML form? What makes you think your user will be different.

Of course the "entering of spaces" can be tested. That is, you can test to see if the user has entered only spaces by trimming any leading and trailing spaces using PHP's trim() function:

if( (trim($username) == "") || (trim($username) == "") || (trim($username) == "") ){
	print "unfortunately there's something....";
}

As is apparent, the relational operators are reaaally useful but they can only go so far - performing minimal validation and testing. Beyond that... you will need something a little more powerful.

A technique called pattern matching is employed. This (pattern matching) is done using regular expressions.... Straight to Lesson 7.

<< The Form Data | Straight to Lesson 7 >>

JamHitz Productions