Development
How to Keep Form Input After a Validation Error

Keep form input after a validation error by rendering the submitted values back into the form after validation, escaping each value for its output context. Preserve ordinary fields, show actionable errors, and deliberately clear secrets.
A form should ask the reader to fix the invalid field, not reconstruct every valid answer because one value was rejected.
Keep form input after a validation error in PHP
Save this self-contained PHP 8.1+ example as form.php and serve it locally with PHP's development server. It validates and redisplays a name and email address without sending email or writing data.
<?php
declare(strict_types=1);
/** Returns a scalar submitted string without accepting nested fields. */
function field(string $key): string
{
$value = $_POST[$key] ?? '';
return is_string($value) ? trim($value) : '';
}
/** Escapes a value for a quoted HTML attribute or text node. */
function escape(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$name = '';
$email = '';
$errors = [];
$valid = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = field('name');
$email = field('email');
if ($name === '' || strlen($name) > 100) {
$errors['name'] = 'Enter a name of at most 100 bytes.';
}
if (strlen($email) > 254 || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Enter a valid email address.';
}
$valid = $errors === [];
if (!$valid) {
http_response_code(422);
}
}
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Contact details example</title>
<h1>Contact details</h1>
<?php if ($valid): ?>
<p>The details passed validation. Nothing was stored or sent.</p>
<?php endif; ?>
<form method="post">
<label for="name">Name</label>
<input id="name" name="name" value="<?= escape($name) ?>"
aria-describedby="name-error" required>
<p id="name-error"><?= escape($errors['name'] ?? '') ?></p>
<label for="email">Email</label>
<input id="email" name="email" type="email" value="<?= escape($email) ?>"
aria-describedby="email-error" required>
<p id="email-error"><?= escape($errors['email'] ?? '') ?></p>
<button type="submit">Validate details</button>
</form>
</html>
The example measures its name limit in bytes, and says so. A production form promising a character limit should implement that contract with the intended Unicode handling.
The htmlspecialchars reference explains the output conversion. PHP's filter validation documentation describes email validation; it does not prove that a mailbox exists.
Separate validation from output safety
Validation decides whether an input meets a rule. Escaping decides how to represent the resulting value safely in HTML. A name containing an apostrophe can be valid and still needs escaping in a quoted attribute.
Try a value containing quotation marks and angle brackets. The form should display the characters as text, not create another attribute or element. Reject or normalize nested fields deliberately rather than passing arrays to string functions.
Browser validation helps usability, but the server must repeat the rules because a request does not have to originate from your form.
Decide what should never be repopulated
Do not redisplay a password, one-time recovery code, payment security code, or secret API credential. Explain clearly when the reader needs to re-enter a sensitive value. Browsers also restrict repopulating file inputs; preserve related text fields and ask for the file again.
For a long form, avoid storing the entire request body in an unrestricted session or application log. Preserve only the fields needed for the next step, and apply a retention limit.
Choose direct redisplay or a redirect deliberately
This example directly redisplays a failed POST and performs no side effect. A production workflow that accepts a submission should generally redirect after success so refreshing the confirmation page does not casually repeat the POST.
If validation errors must survive a redirect, keep selected values and errors in a short-lived session record and remove them after display. Avoid putting personal form values in the URL, where history, logs, and referrers can expose them.
A redirect alone is not an idempotency guarantee for a data-writing endpoint. Duplicate-submission prevention needs its own server-side contract.
What should I test?
Submit a valid name with an invalid email, then reverse them. Verify both scalar values remain visible, the correct field has an error, and a later valid submission has no stale errors. Test nested fields and HTML-like input directly with a request client.
For a broader review of input and output boundaries, use the PHP code review checklist or discuss the form workflow.