Souping Up the Script

   

You can soup up this script to be smarter:

Check for Spaces

This script as it currently is can be easily fooled if a user just enters spaces in each of the fields. In the check_form script on lines 46 and 50, we check to see if the user entered anything. This includes spaces. If we want to make sure the users enter characters (not just spaces), we could check like this:

 if(ereg("^ +", $last)) {      $error[last] = true;     $print_again = true; } 

Basically, the ereg() function is checking the $last variable to see if it starts with one or more spaces. We'll take a closer look at the ereg() function a little later in this chapter.

Check for Minimum Number of Characters

Sometimes you may want to make sure the user enters a minimum number of characters. It's easy enough to enforce a limit on the maximum number of characters that a user can enter, by using the maxlength attribute on an HTML input tag for example, <input type="text" maxlength="24">.

 if(strlen($first) < 3) {        $error[first] = true;       $print_again = true;   } 

Here we use the strlen() function (string length) to see if the $first variable contains at least three characters. If it has zero, one, or two characters then we throw an error.

Add More Error Information

It's also useful to add a little extra error information. We can modify our examples above slightly:

   if(strlen($first) < 3) {        $error['first'] = "Please enter more than two characters in this field. ";       $print_again = true;   }   if(ereg("^ +", $last)) {       $error['last'] = "Please enter characters in this field, not spaces. ";       $print_again = true;   } 

Here, instead of assigning the $error variable a true value, we can add a short description of the error. Then if we modify our error_flag function as follows, we can print this message out to the users when we display the form to them again:

 function error_flag($error, $field) {        if($error[$field]) {         print("<td class=error>$error[$field]");       } else {          print("<td>");       } } //end function error_flag 

   
Top


Advanced PHP for Web Professionals
Advanced PHP for Web Professionals
ISBN: 0130085391
EAN: 2147483647
Year: 2005
Pages: 92

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net