PHP Forms Redisplaying Forms with Inline Error Messages - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Forms Redisplaying Forms with Inline Error Messages - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Tuesday, June 4, 2019

PHP Forms Redisplaying Forms with Inline Error Messages

PHP Forms 


Redisplaying Forms with Inline Error Messages

Problem

When there’s a problem with data entered in a form, you want to print out error messages alongside the problem fields, instead of a generic error message at the top of the form.

You also want to preserve the values the user entered in the form, so they don’t have to redo the entire thing.

Solution

As you validate, keep track of form errors in an array keyed by element name. Then, when it’s time to display the form, print the appropriate error message next to each element. To preserve user input, use the appropriate HTML idiom: a value attribute (with entity encoding) for most <input/> elements, a checked='checked' attribute for radio buttons and checkboxes, and a selected='selected' attribute on <option/> elements in drop-down menus.

Example   Redisplaying a form with error messages and preserved input

The main logic and validation function:

       // Set up some options for the drop-down menu
       $flavors = array('Vanilla','Chocolate','Rhinoceros');

       // Set up empty defaults when nothing is chosen.
       $defaults = array('name' => ' ',
                                        'age' => ' ',
                                        'flavor' => array());
       foreach ($flavors as $flavor) {
       $defaults['flavor'][$flavor] = ' ';
       }

       if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            $errors = array();
            include __DIR__ . '/show-form.php';
       } else {
            // The request is a POST, so validate the form
            $errors = validate_form();
            if (count($errors)) {
                // If there were errors, redisplay the form with the errors,
                // preserving defaults
                if (isset($_POST['name'])) { $defaults['name'] = $_POST['name']; }
                if (isset($_POST['age'])) { $defaults['age'] = "checked='checked'"; }
                foreach ($flavors as $flavor) {
                    if (isset($_POST['flavor']) && ($_POST['flavor'] == $flavor)) {
                         $defaults['flavor'][$flavor] = "selected='selected'";
                    }
                }
                include __DIR__ . '/show-form.php';
            }else {
                // The form data was valid, so congratulate the user. In "real life"
                // perhaps here you'd redirect somewhere else or include another
                // file to display
                print 'The form is submitted!';
            }
       }
       
       function validate_form() {
            global $flavors;

            // Start out with no errors
            $errors = array();

            // name is required and must be at least 3 characters
            if (! (isset($_POST['name']) && (strlen($_POST['name']) > 3))) {
                 $errors['name'] = 'Enter a name of at least 3 letters';
            }
            if (isset($_POST['age']) && ($_POST['age'] != '1')) {
                 $errors['age'] = 'Invalid age checkbox value.';
            }
            // flavor is optional but if submitted must be in $flavors
            if (isset($_POST['flavor']) && (! in_array($_POST['flavor'], $flavors))) {
                 $errors['flavor'] = 'Choose a valid flavor.';
            }
    
            return $errors;
       }

The form (show-form.php):

        <form action='<?= htmlentities($_SERVER['SCRIPT_NAME']) ?>' method='post'>
       <dl>
       <dt>Your Name:</dt>
       <?php if (isset($errors['name'])) { ?>
           <dd class="error"><?= htmlentities($errors['name']) ?></dd>
       <?php } ?>
       <dd><input type='text' name='name'
                  value='<?= htmlentities($defaults['name']) ?>'/></dd>
       <dt>Are you over 18 years old?</dt>
       <?php if (isset($errors['age'])) { ?>
            <dd class="error"><?= htmlentities($errors['age']) ?></dd>
       <?php } ?>
       <dd><input type='checkbox' name='age' value='1'
                         <?= $defaults['age'] ?>/> Yes</dd>
       <dt>Your favorite ice cream flavor:</dt>
       <?php if (isset($errors['flavor'])) { ?>
            <dd class="error"><?= htmlentities($errors['flavor']) ?></dd>
       <?php } ?>
       <dd><select name='flavor'>
       <?php foreach ($flavors as $flavor) { ?>
       <option <?= isset($defaults['flavor'][$flavor]) ?
                               $defaults['flavor'][$flavor] :
                               " " ?>><?= htmlentities($flavor) ?></option>
       <?php } ?>
       </select></dd>
       </dl>
       <input type='submit' value='Send Info'/>
       </form>

Discussion

When a form is submitted with invalid data, it’s more pleasant for the user if the form is redisplayed with error messages in appropriate places rather than a generic the form is invalid message at the top of the form. The validate_form() function builds up an array of error messages that the form display code uses to print the messages in the right places.

Extending a matter of expanding the checks in validate_form() to handle the appropriate validation needs of your form and including the correct HTML generation in show form.php so that the form includes the input elements you want.



No comments:

Post a Comment

Post Top Ad