Form Checking & Displaying Errors

A friend emailed me tonight and asked how I output form errors onto a page once a user has submitted invalid data. Rather than email him back, I’ll post an abbreviated version of my preferred method here.

My friend wrote about 50 lines of code to accomplish what we do in about 10 below. I like this code simply because it allows me to add errors to a complex form when I see the need… and those errors are automatically included in the error array and rendered in a html list (that can be easily formatted). The checks on the form below are there present for the purposes of illustrating my point only.

<?php
// Create array to store error values
$arrErrors = array();

// Error checking
if (ereg('[^a-zA-Z]', $fn)) $arrErrors['fne'] = 'First name can contain letters only.';
if ($fnl < 2) ) $arrErrors['fnl'] = 'First name must be more than two characters.';

// If errors are visible...
if (count($arrErrors) != 0) {

// Add error text to an error string of text.
$strError = '<b>Please correct the following errors:</b><ul>';

// Get each error and add it to the error string as a list item.
foreach ($arrErrors as $error) {
$strError .= "<li>$error</li>";
}
$strError .= '</ul>';

// Output error to screen
echo "$strError";
}
?>
First Name:
Your Email Address:
 


If you liked this article, you may also like:

  1. Post a Form with CURL (and How Spammers Automate Spam Comments to WordPress)
  2. Email subscription form in your RSS feed?
  3. WordPress Automatic Install and Upgrade Errors
  4. Email Style Priority Field in a Form
  5. PHP function to generate random password string
About Marty

is a passionate web developer from Sydney, Australia. He owns about 600 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. Follow Marty on Twitter or Google+.

Please leave a comment or question!

*