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";
}
?>
|
|
If you liked this article, you may also like:


Recent Comments