Sub topic 13
Keeping user input and helping people recover
This chapter assumes you have read the earlier chapters on error messages and accessible errors. You should know basic server-rendered HTML forms and be able to read short Python and JavaScript examples.
An error message tells people what went wrong. Recovery decides whether they finish the form. If a failed submit wipes the form, the user must retype everything. Many will leave instead.
The core rule: an error never costs the user their work
When validation fails, put back everything the user entered, except a small set of values that should never be echoed. Then mark only the fields that need attention.
Input is lost in more places than the submit button. The common ones are:
- The server re-renders a blank form after a failed validation.
- A script calls
form.reset()or replaces the form's HTML after an error. - The user presses Back or Refresh and the browser discards the page state.
- The session expires while the user is writing a long answer.
- The user closes the tab or navigates away by accident.
- A slow network leads to a second click, a second submission, and a confusing duplicate.
The sections below cover each of these.
flowchart TDThe diagram below is the target flow. A failed submit loops back to the same form with the data intact. Only a successful submit clears the saved state.
Re-rendering with the submitted values
For a server-rendered form, the server sends back the values it received. Escape every value. A value placed in an attribute without escaping is a cross-site scripting hole.
This Flask example validates two fields and returns the form with the user's input on failure. Flask's render_template_string escapes {{ }} values by default.
from flask import Flask, request, redirect, render_template_string
app = Flask(__name__)
PAGE = """
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{{ 'Error: ' if errors }}Contact us</title></head>
<body>
<h1>Contact us</h1>
{% if errors %}
<div role="alert" tabindex="-1" id="error-summary">
<h2>There is a problem</h2>
<ul>
{% for field, message in errors.items() %}
<li><a href="#{{ field }}">{{ message }}</a></li>
{% endfor %}
</ul>
</div>
{% endif %}
<form method="post" novalidate>
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email"
value="{{ values.get('email', '') }}"
{% if 'email' in errors %}aria-invalid="true" aria-describedby="email-error"{% endif %}>
{% if 'email' in errors %}<p id="email-error">Error: {{ errors['email'] }}</p>{% endif %}
<label for="message">Message</label>
<textarea id="message" name="message" rows="6"
{% if 'message' in errors %}aria-invalid="true" aria-describedby="message-error"{% endif %}>{{ values.get('message', '') }}</textarea>
{% if 'message' in errors %}<p id="message-error">Error: {{ errors['message'] }}</p>{% endif %}
<button type="submit">Send message</button>
</form>
</body>
</html>
"""
@app.route("/", methods=["GET", "POST"])
def contact():
values, errors = {}, {}
if request.method == "POST":
values = {
"email": request.form.get("email", "").strip(),
"message": request.form.get("message", "").strip(),
}
if "@" not in values["email"]:
errors["email"] = "Enter an email address in the format [email protected]"
if not values["message"]:
errors["message"] = "Enter a message"
if not errors:
# Save the message here, then redirect so Refresh does not resubmit.
return redirect("/thanks", code=303)
status = 422 if errors else 200
return render_template_string(PAGE, values=values, errors=errors), status
@app.route("/thanks")
def thanks():
return "<h1>Thank you</h1>"
if __name__ == "__main__":
app.run(debug=True)Several details in this example matter:
- The
<textarea>content sits between its tags, not in avalueattribute. Putting avalueattribute on a textarea does nothing. - The summary links point at field ids, so each link moves the user straight to the field to fix.
- The page title starts with "Error:". Screen reader users hear the title first on a full page load, so this tells them the submit failed.
- The success path redirects with status 303. This is the Post/Redirect/Get pattern. Refreshing the confirmation page does not send the form again.
- The
422status is optional for users but lets monitoring tell failed validations from successes.
What not to echo back
Do not repopulate these values:
- Passwords and password confirmations. Echoing them puts the secret in the page source. Ask the user to retype them, and say so in the error text.
- Card numbers, security codes, and one-time codes. Tell the user which field to re-enter.
- File inputs. Browsers do not allow a script or server to set a file input's value. Tell the user that the file must be chosen again, and show the name of the file they chose earlier if you kept it.
Client-side validation must not reset the form
Scripts that validate on submit should call event.preventDefault() and leave the fields alone. Never rebuild the form's HTML to show an error. Insert or update the error elements only. Rebuilding replaces the inputs, which drops the user's text, selection, and focus position.
Saving drafts for long or valuable input
Some input is expensive to retype: a long message, an application essay, a support request. Save a draft as the user types, so a lost session, crash, or accidental navigation does not destroy it.
This script saves text fields to sessionStorage and restores them on load. It skips password fields and any field marked data-no-draft.
const form = document.querySelector('form');
const DRAFT_KEY = 'draft:' + location.pathname;
const draftFields = [...form.elements].filter(
(el) =>
el.name &&
(el.tagName === 'TEXTAREA' ||
(el.tagName === 'INPUT' && ['text', 'email', 'tel', 'search'].includes(el.type))) &&
!el.hasAttribute('data-no-draft')
);
function saveDraft() {
const draft = {};
for (const el of draftFields) draft[el.name] = el.value;
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(draft));
}
function restoreDraft() {
const raw = sessionStorage.getItem(DRAFT_KEY);
if (!raw) return;
const draft = JSON.parse(raw);
for (const el of draftFields) {
// Do not overwrite values the server just sent back.
if (el.value === '' && draft[el.name]) el.value = draft[el.name];
}
}
form.addEventListener('input', saveDraft);
form.addEventListener('submit', () => sessionStorage.removeItem(DRAFT_KEY));
restoreDraft();Know the limits of this approach:
sessionStoragelasts for the tab's lifetime. UselocalStorageif the draft should survive closing the browser, and accept that it also persists on shared computers.- The script clears the draft on submit. If the server then rejects the data, the server re-rendered values are your safety net. For fields the server cannot echo, clear the draft only after a confirmed success.
- Do not save sensitive data this way. Storage is readable by any script on the page.
- Tell users when you restored something, for example "We restored your unsent message." A silent restore can confuse people who expect an empty form.
Leaving the page by accident
A beforeunload handler asks the browser to show a confirmation dialog when the user tries to leave. Use it only when the form has unsaved changes, and remove it as soon as the user submits.
let dirty = false;
form.addEventListener('input', () => { dirty = true; });
form.addEventListener('submit', () => { dirty = false; });
window.addEventListener('beforeunload', (event) => {
if (dirty) event.preventDefault();
});Browsers show their own generic text and ignore custom messages. Do not attach this to every form. A prompt on a one-field search box is noise, and users learn to dismiss it.
Back, Refresh, and browser autofill
Browsers restore form values when the user returns with the Back button, but only if the page can come from the back/forward cache or the form was not rebuilt by script. Three habits break this:
- Setting
Cache-Control: no-storeon form pages can stop the browser from restoring values. Use it for pages that show private data, but know the cost. - Building the form entirely in JavaScript after load gives the browser nothing to restore.
- Adding
autocomplete="off"to ordinary fields blocks both restoration and autofill. Reserve it for cases such as one-time codes or fields where a stored value would be wrong.
Session timeouts
A session that expires while the user types a long answer is one of the worst failures, because the submit succeeds technically and the work is lost. Reduce the risk:
- Warn before expiry, with enough time to act, and let the user extend the session without leaving the page.
- If the session does expire, accept the POST, ask the user to sign in again, and then resume the original submission with their data. Do not drop the body of the request.
- Save a draft server-side for forms that take more than a few minutes.
Preventing duplicate submissions
Slow responses lead people to click twice. Two common defenses are:
- On submit, set a flag and ignore later submits. Do not use the
disabledattribute on the button alone. A disabled button leaves the tab order, so focus can jump unexpectedly, and some screen readers skip it. Usearia-disabled="true"and ignore clicks instead, and add a visible "Sending…" text. - Add an idempotency token, a random value stored in a hidden field and checked by the server, so a repeated POST with the same token is treated as the same request.
The server check is the reliable one, because a script cannot stop a user refreshing a POST response or a flaky connection retrying.
Helping people recover, not just retry
Recovery is more than restoring text. These practices help people finish:
- Keep error messages next to their fields, and keep the summary until the problems are fixed.
- Say what was kept and what was not. "Your message has been kept. Enter your password again" is better than a silent blank field.
- Offer a clear route out of a dead end, such as a support link on a form that fails repeatedly.
- On a server failure (a 500 error, not a validation error), keep the form as it was and say that the problem is not the user's fault. Offer to try again.
- Allow edits after a confirmation step. A review page should link back to the form with the values still filled in.
Quick reference
| Situation | Keep the input? | How |
|---|---|---|
| Validation fails on the server | Yes, except secrets | Re-render with escaped values |
| Validation fails in the browser | Yes | `preventDefault()`, update only error elements |
| Password or card fields | No | Clear and say why |
| File input | No (browser rule) | Ask the user to choose the file again |
| Long text, tab closed or crashed | Yes | Draft in storage, restore on load |
| Session expired | Yes | Resume the POST after sign-in |
| Double click or retry | One submission | `aria-disabled` plus server token |
Exercise
A user fills in a registration form with a name, email, password, and a 400-word bio. They submit it with an invalid email. Your server re-renders the form. Which values should the re-rendered form contain, and what should it say about the rest?
Show answer
It should contain the name, the email (with the invalid text, so the user can correct it instead of retyping), and the full bio, all escaped before they are written into the HTML. It should not echo the password. The password field should be empty, with a short note such as "For your security, enter your password again." The page should also show an error summary, an error message tied to the email field with aria-describedby, and aria-invalid="true" on that field only.
Exercise
A teammate wants to stop double submissions by adding disabled to the submit button in a click handler. Give one problem with this and a better approach.
Show answer
A disabled button is removed from the tab order, so keyboard focus can be lost, and some screen readers skip it. If the request fails, the user may also be left with a button that stays dead. A better approach is to set aria-disabled="true", ignore further clicks while a request is in flight, show visible "Sending…" text, and have the server reject repeated submissions with an idempotency token. Re-enable the button if the request fails.