InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Redisplaying Forms with Inline Error Messages in PHP
PHP

Redisplaying Forms with Inline Error Messages in PHP

InfinityCoder November 29, 2016

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.

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 9-22 displays and validates a form with a text box, a checkbox, and a drop-down menu.
Example 9-22. Redisplaying a form with error messages and preserved input
The main logic and validation function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<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>

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 in Example 9-22 builds up an array of error messages that the form display code uses to print the messages in the right places.
Extending Example 9-22 is 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.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Installing PECL Packages in PHP
You want to install a PECL package; this builds a …

Installing PECL Packages in PHP

Making New Directories in PHP
You want to create a directory. Use mkdir(): The second …

Making New Directories in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap