PHP Form Validation: Displaying error messages with form

This entry is part 1 of 7 in the series PHP Form Validation

Form validation is important as users could be careless with the data they have entered into the form.

We need to display some error messages when users have entered them incorrectly.

We use here a different method to display an error message as compare to an earlier post.


// Logic to do the right thing based on
// the hidden submit_check parameter
if ($_POST['submit_check']) {
    // If validate_form( ) returns errors, pass them to show_form( )
    if ($form_errors = validate_form()) {
    } else {
} else {

// Do something when the form is submitted
function process_form()
    print 'Hello, ' . $_POST['my_name'];

// Display the form
function show_form($errors = '')
    // If some errors were passed in, print them out
    if ($errors) {
        print 'Please correct these errors: <ul><li>';
        print implode('</li><li>', $errors);
        print '</li></ul>';

    print <<< html_output
<form method='POST' action='$_SERVER[PHP_SELF]'>
Your name: <input type='text' name='my_name'>
<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>

// Check the form data
function validate_form()
    // Start with an empty array of error messages
    $errors = array();

    // Add an error message if the name is too short
    if (strlen($_POST['my_name']) < 3) {
        $errors[] = 'Your name must be at least 3 letters long.';

    // Return the (possibly empty) array of error messages
    return $errors;


In line 23, $errors = ” is the default for $errors¬†variable. It is an empty string and resolved to false and so if there is no variable, the form is always shown.

In line 28, we also use a common method implode to join an $errors array element with the string </li><li>.

Series Navigation
PHP Form Validation: Required elements >>