|
Sams Teach Yourself PHP in 10 Minutes Authors: Newman C Published year: 2005 Pages: 66-69/151 |
SummaryIn this lesson you have learned how to generate HTML components on-the-fly and learned some techniques for creating dynamic form input objects. In the next lesson you will learn how to perform validation on an HTML form. |
Lesson 13. Form ValidationIn this lesson you will learn some techniques for validating form input in a user -friendly way. The principles of validating user-submitted input are fairly straightforward: Just check each item in $_POST in turn and make sure it matches a set of criteria. However, making sure the user is able to correct any mistakes and resubmit the form with a minimum of fuss presents a bit more of a challenge. |
Enforcing Required FieldsThe most basic type of form validation is to enforce that a particular field must contain a value. In the case of a text input that is submitted with no value entered, the element in $_POST is still created, but it contains an empty value. Therefore, you cannot use isset to check whether a value was entered; you must check the actual value of the element, either by comparing it to an empty string or by using the following, more compact syntax with the Boolean NOT operator:
if (!$_POST["fieldname"]) { ... }
Because each field on the form creates an element in $_POST , if every field requires a value to be entered, you could use a simple loop to check that there are no empty values in the array:
foreach($_POST as $field => $value) {
if (!$value) {
$err .= "$field is a required field <br>";
}
}
if ($err) {
echo $err;
echo "Press the back button to fix these errors";
}
else {
// Continue with script
}
Rather than exit as soon as an empty field is found, this script builds up an error string, $err . After the validation is done, the contents of $err are displayed if there are any errors. If there are no errors, $err is empty, and script execution continues with the else clause.
One obvious limitation of this approach is that you cannot pick which fields require a value; every posted field must have been completed. You could improve upon this by supplying a list of required fields in the script, and by using an associative array, you can also provide a label for each field to display in the warning message:
$required = array("first_name" => "First name",
"email" => "Email address",
"telephone" => "Telephone number");
foreach($required as $field => $label) {
if (!$_POST[$field]) {
$err .= "$label is a required field <br>";
}
}
|
Displaying Validation WarningsAnother issue to consider is where to send the user when validation fails. So far we have assumed that a form submits to a processing script, and when one or more validation errors are found, the form prompts the user to use his or her browser's Back button to fix the errors. Not only does this create one more step for the user to take in order to complete the formand in an online store, you want as few obstacles between a customer and a completed order as possibleit can also sometimes cause the data in the form fields to be lost when Back is clicked. Whether the Back button causes data to be lost usually depends on the cache settings, either on the web server, in the user's browser, or at the user's Internet service provider. In many cases there is no problem. However, most notably when a PHP session has been started, no-cache headers are automatically sent to the browser, which causes data in form fields to be reset to their original values when you click the Back button. You will learn more about PHP sessions in Lesson 14, "Cookies and Sessions." A good technique is to have the form and processing script in the same file and have the form submit to itself. This way, if there are errors, they can be displayed on the same page as the form itself, and the previously entered values can be automatically defaulted into the form. Listing 13.1 shows a fairly complete example of a registration form, register.php . The name and email address fields are required, but the telephone number is optional. Listing 13.1. A Sample Registration Form with Required Fields
<?php
$required = array("name" => "Your Name",
"email" => "Email Address");
foreach($required as $field => $label) {
if (!$_POST[$field]) {
$err .= "$label is a required field <br>";
}
}
if ($err) {
echo $err;
?>
<FORM ACTION="register.php" METHOD=POST>
<TABLE BORDER=0>
<TR>
<TD>Your Name</TD>
<TD><INPUT TYPE=TEXT SIZE=30 NAME="name"
VALUE="<?php echo $_POST["name"];?>"></TD>
</TR>
<TR>
<TD>Email Address</TD>
<TD><INPUT TYPE=TEXT SIZE=30 NAME="email"
VALUE="<?php echo $_POST["email"];?>"></TD>
</TR>
<TR>
<TD>Telephone</TD>
<TD><INPUT TYPE=TEXT SIZE=12 NAME="telephone"
VALUE="<?php echo $_POST["telephone"];?>"></TD>
</TR>
</TABLE>
<INPUT TYPE=SUBMIT VALUE="Register">
</FORM>
<?php
}
else {
echo "Thank you for registering";
}
?>
Note that the warning messages in this example appears even if the form has not yet been submitted. This could be improved by also checking for the existence of the $_POST array in the script by using is_array , but the check for $err would also need to look for $_POST ; otherwise , the form would never be displayed. The condition that checks $err spans the HTML form and, even though the PHP tags are closed around this chunk of HTML, the form is displayed only if that condition is true. In this example, after the form has been completed successfully, only a simple message is displayed. This is where you would do any processing based on the submitted data, such as storing it to a database, which you will learn about in Lesson 19, "Using a MySQL Database." Alternatively, the script could force the browser to redirect the user to another page automatically by using a Location HTTP header, as follows :
header("Location: newpage.php");
|
|
Sams Teach Yourself PHP in 10 Minutes Authors: Newman C Published year: 2005 Pages: 66-69/151 |