HTML Form Validation That Explains Errors: The Constraint Validation API
A contact form has two ways to reject an email address before it sends anything. An empty field needs an address. A value like alex@ needs a domain. Showing “Invalid input” in both cases leaves the reader to guess what to fix. HTML can already tell those errors apart.
Let the control describe the problem
Give the input a visible label, a name and the constraints you actually need:
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required>
Read email.validity.valueMissing for an empty required field and email.validity.typeMismatch for a value the email control cannot accept. A syntactically valid address can still lead to a nonexistent mailbox. For a text area, minlength measures UTF-16 code units, so an emoji can count as more than one unit.
If the native messages suit your form, the browser can display them on submission. In a script, checkValidity() returns the result and fires an invalid event on a failing control. reportValidity() also asks the browser to show the problem. The following example reads the same validity flags to place guidance beneath each field.
Try the contact form
Save the example as form-demo.html and open it locally. Submit it empty, fix the first address, then enter a different address in the confirmation field. Use the keyboard to return to the first field and change it to match. The confirmation error should clear too. The demo checks the fields locally and sends nothing.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Accessible form validation</title>
<style>
* { box-sizing: border-box; }
body { font: 1rem/1.5 system-ui, sans-serif; max-width: 42rem;
margin: 2rem auto; padding: 0 1rem; color: #18232d; }
label { display: block; font-weight: 650; margin-top: 1.1rem; }
input, textarea { display: block; width: 100%; padding: .65rem;
border: 1px solid #627181; border-radius: .3rem; font: inherit; }
:is(input, textarea):focus-visible, button:focus-visible {
outline: 3px solid #165f9c; outline-offset: 2px; }
[aria-invalid="true"] { border: 2px solid #a32020; }
.error { color: #8d1c1c; min-height: 1.3rem; margin: .25rem 0; }
.hint { color: #344553; font-size: .92rem; }
.summary { margin-top: 1.25rem; padding: .8rem; border-left: 4px solid #165f9c; }
button { margin-top: 1rem; padding: .7rem 1.2rem; font: inherit; cursor: pointer; }
</style>
</head>
<body>
<main>
<h1>Send a message</h1>
<p>All fields are required. This demo checks the form but does not send it.</p>
<noscript>Enable JavaScript to run this local demo.</noscript>
<form id="contact">
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email"
aria-describedby="email-error" required>
<p class="error" id="email-error"></p>
<label for="confirm-email">Confirm email address</label>
<input id="confirm-email" name="confirmEmail" type="email"
autocomplete="email" aria-describedby="confirm-email-error" required>
<p class="error" id="confirm-email-error"></p>
<label for="message">Message</label>
<p class="hint" id="message-hint">Enter at least 10 characters.</p>
<textarea id="message" name="message" rows="5" minlength="10"
aria-describedby="message-hint message-error" required></textarea>
<p class="error" id="message-error"></p>
<button type="submit" disabled>Check message</button>
<p id="form-summary" class="summary" role="status"></p>
</form>
</main>
<script>
const form = document.querySelector('#contact');
const email = document.querySelector('#email');
const confirmEmail = document.querySelector('#confirm-email');
const summary = document.querySelector('#form-summary');
const fields = [...form.querySelectorAll('input, textarea')];
function updateCrossFieldRule() {
const differs = confirmEmail.value !== '' &&
confirmEmail.value !== email.value;
confirmEmail.setCustomValidity(
differs ? 'The email addresses do not match.' : ''
);
}
function errorText(field) {
const v = field.validity;
if (v.valueMissing) return 'Please fill out this field.';
if (v.typeMismatch) return 'Enter a valid email address.';
if (v.tooShort) return `Use at least ${field.minLength} characters.`;
if (v.customError) return field.validationMessage;
return 'Please check this value.';
}
function showFieldState(field) {
const error = document.getElementById(`${field.id}-error`);
const valid = field.validity.valid;
error.textContent = valid ? '' : errorText(field);
if (valid) field.removeAttribute('aria-invalid');
else field.setAttribute('aria-invalid', 'true');
return valid;
}
let submitted = false;
fields.forEach(field => field.addEventListener('input', () => {
updateCrossFieldRule();
if (submitted) showFieldState(field);
// If the first email changes, recheck its confirmation as well.
if (submitted && field === email) showFieldState(confirmEmail);
summary.textContent = '';
}));
form.addEventListener('submit', event => {
event.preventDefault(); // Demo only: no network request.
submitted = true;
updateCrossFieldRule();
const invalid = fields.filter(field => !showFieldState(field));
if (invalid.length) {
summary.textContent = `Please correct ${invalid.length} field(s).`;
invalid[0].focus();
return;
}
summary.textContent = 'Checks passed. Connect this form to a server to send it.';
});
form.noValidate = true;
form.querySelector('button').disabled = false;
</script>
</body>
</html>
Keep errors connected to the fields
Each control names its error paragraph in aria-describedby. The message field also names its permanent length hint, so adding an error preserves the original instruction. On the first submit, the script writes each error as text, sets aria-invalid on the affected controls and moves focus to the first one. The status region gives the total. After that, typing can clear errors without moving focus. Try the sequence at 200% zoom and with a screen reader to check the focus order and what gets announced.
Only the confirmation field needs a rule that HTML cannot express. A nonempty message passed to setCustomValidity() keeps that field invalid until the script passes an empty string. Recheck the rule when either address changes. For a multilingual form, translate the messages you supply. The guide to accessible color and focus states covers how to make an error visible alongside its text.
Give the server the same tests
In the demo the script enables the button after registering the submit handler and sets form.noValidate so the browser hands submission to that handler. For a real contact form, supply a working action and method="post" and an enabled submit button in the HTML. Keep native validation available until your enhancement initializes. On a server-side error, return the field names and actionable messages and preserve the user’s valid entries.
Test the endpoint independently with a missing email, a malformed address and a message over your size limit. Browser checks help someone complete a form. The server still has to enforce the rules before storing or sending the message. Use the format the endpoint accepts: the guide to JSON, form data and multipart requests shows how to send each with cURL. In the cURL command builder, prepare a request with a missing field and check the response from your test endpoint. When displaying a rejected value, keep it as text, as described in HTML escaping and sanitizing.