Enforcing Required Fields


The 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.

Validation Warnings Always show all the warning messages that relate to the submitted data straight away. You should give your users the opportunity to correct their errors all at one time.


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>";   } } 



    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

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