tags:

views:

99

answers:

3

My php form has required fields, but the message does not let the user know which field hasn't been entered. How can I do this?

//if statement to check required fields
if ($name && $phone && $email && && $address && $city && $state && $zip && $month && $date && $year && $contact)...
    //if some required fields were not filled out
    echo "Please make sure you fill in all required fields<br>Click <a href=\"javascript:history.back(1)\">here</a> to return to our form.";
}
+7  A: 

Here is a trivial example...

// An array of required fields, these fields must not be empty
$requiredFields = array('name', 'email');  

// Iterate through required fields
foreach ($requiredFields as $fieldName)
{
    // Does this field have a value?
    if (empty($_REQUEST[$fieldName]))
    {
        echo 'rawr! go back and fill out ' . $fieldName . "<br>\n";
    }
}    
John Himmelman
A: 

It looks like each of those are boolean values; I assume you set them earlier when checking each value individually. Instead of using a single echo at the end, I would initialize a $message variable at the beginning, and put all error messages there. At the end, just echo $message'.

eykanal
A: 

Just tedious if/else clauses. You could use a validation framework to elemiate alot of this.

if (empty($name))
   echo "Name is not filled out";
if(empty($phone))
   echo "Phone is not filled out";

If you want to get fancy this would work

foreach (array("name","phone") as $var)
{
   if (empty($$name))
      echo "$var is not filled out";
}
Byron Whitlock