Form validation with HTML and a little JavaScript
Use the browser's own rules first, tie each error to its field, and add a summary.
What you will be able to do
- Choose input types and labels that let the browser check a value
- Write required, minlength, min, max and pattern rules
- Style invalid fields with :user-invalid without colour alone
- Show your own messages and move focus to an error summary
- State what a check in the browser cannot do for you
Labels and input types
Validation starts with the markup. Give every field a label and tie it to the field with for and id. The label names the field for assistive technology, and clicking the label puts the cursor in the field.
Then choose the input type that matches the value. A field of type="email" or type="number" makes the browser check the shape of the value, and a phone shows a fitting keyboard. You write no code for either.
required, pattern and the other rules
The browser checks a field against the rules in its attributes before it sends the form. If a field fails, it refuses to send and shows its own message next to the field.
required: the field must not be empty.minlengthandmaxlength: the least and most characters.minandmax: the lowest and highest number or date.pattern: a regular expression that the whole value must match.
The pattern is wrapped so that it must match from the first character to the last, so you do not write anchors. Describe the pattern in visible text near the field, because the person cannot read a regular expression. For a field that has to be an email address, use type="email" and do not write your own pattern for it.
Keep each pattern short and without nested repeats, such as a group that repeats inside a group that repeats. The patterns in these examples contain one fixed shape each, and the verification script for this page checks that none of them nests a repeat.
HTML
<form class="form-native" id="form-native" aria-labelledby="form-native-title">
<h2 class="form-native__title" id="form-native-title">Join the example club</h2>
<p class="form-native__field">
<label for="form-native-name">Name</label>
<input id="form-native-name" aria-describedby="form-native-name-error" name="name" type="text" autocomplete="name" required minlength="2">
<span class="form-native__error" id="form-native-name-error" data-message="Enter a name of at least 2 characters."></span>
</p>
<p class="form-native__field">
<label for="form-native-email">Email address</label>
<input id="form-native-email" aria-describedby="form-native-email-error" name="email" type="email" autocomplete="email" required>
<span class="form-native__error" id="form-native-email-error" data-message="Enter an address such as name@example.com."></span>
</p>
<p class="form-native__field">
<label for="form-native-seats">Seats (1 to 10)</label>
<input id="form-native-seats" aria-describedby="form-native-seats-error" name="seats" type="number" inputmode="numeric" min="1" max="10" required>
<span class="form-native__error" id="form-native-seats-error" data-message="Enter a whole number from 1 to 10."></span>
</p>
<p class="form-native__field">
<label for="form-native-code">Member code</label>
<input id="form-native-code" name="code" type="text" pattern="[A-Z]{3}-[0-9]{4}" required aria-describedby="form-native-code-hint form-native-code-error">
<span class="form-native__hint" id="form-native-code-hint">Three capital letters, a hyphen, four digits. Example: ABC-1234.</span>
<span class="form-native__error" id="form-native-code-error" data-message="The code does not match that shape."></span>
</p>
<p><button class="form-native__submit" id="form-native-submit">Join</button></p>
<p class="form-native__status" id="form-native-status" role="status"></p>
</form>CSS
.form-native {
--fn-bg: #ffffff;
--fn-fg: #1b1f2a;
--fn-muted: #4a5163;
--fn-line: #6b7280;
--fn-accent: #3730a3;
--fn-on-accent: #ffffff;
--fn-bad: #b42318;
max-width: 26rem;
padding: 1rem;
color: var(--fn-fg);
background: var(--fn-bg);
}
.form-native__title { margin: 0 0 1rem; font-size: 1.25rem; }
.form-native__field { display: grid; gap: 0.25rem; margin: 0 0 1rem; }
.form-native__field label { font-weight: 600; }
.form-native__field input {
min-height: 44px;
padding: 0.25rem 0.5rem;
font: inherit;
color: var(--fn-fg);
background: var(--fn-bg);
border: 1px solid var(--fn-line);
border-radius: 6px;
}
.form-native__field input:focus-visible {
outline: 3px solid var(--fn-accent);
outline-offset: 2px;
}
.form-native__hint { color: var(--fn-muted); font-size: 0.9375rem; }
.form-native__error { display: none; color: var(--fn-bad); font-size: 0.9375rem; font-weight: 600; }
.form-native__field input:user-invalid { border: 3px solid var(--fn-bad); }
.form-native__field:has(input:user-invalid) .form-native__error { display: block; }
.form-native__field:has(input:user-invalid) .form-native__error::after { content: attr(data-message); }
.form-native__submit {
min-height: 44px;
padding: 0.5rem 1.5rem;
font: inherit;
color: var(--fn-on-accent);
background: var(--fn-accent);
border: 1px solid var(--fn-accent);
border-radius: 8px;
cursor: pointer;
}
.form-native__submit:focus-visible {
outline: 3px solid var(--fn-fg);
outline-offset: 2px;
}
.form-native__status { margin: 0; min-height: 1.5em; color: var(--fn-muted); }
@media (prefers-color-scheme: dark) {
.form-native {
--fn-bg: #12141c;
--fn-fg: #eceef5;
--fn-muted: #b6bccb;
--fn-line: #8b93a7;
--fn-accent: #b4b8ff;
--fn-on-accent: #12141c;
--fn-bad: #ff8a80;
}
}JavaScript
// The browser checks the fields first. This script only runs when every field is valid,
// and it stops the preview from sending the form, because a preview cannot send anything.
var form = document.getElementById('form-native');
var statusLine = document.getElementById('form-native-status');
form.addEventListener('submit', function (event) {
event.preventDefault();
statusLine.textContent = 'Example only: every field is valid and nothing was sent.';
});The example has a small script, but it does not check anything. It only stops the preview from sending the form, because a preview cannot send anything.
Styling with :user-invalid
The older :invalid pseudo-class matches as soon as the page loads, so an empty required field is red before anyone has typed. The pseudo-class :user-invalid matches only after the person has interacted with the field, or after a failed attempt to send the form. Use it for the red border.
A border colour alone is not enough, because some people cannot tell the colours apart. The example also thickens the border and shows a text message. The message is added with :has(), so that the field's container shows it when the field is invalid. The words sit in a data-message attribute and appear as generated content, so the message element is empty until it is needed.
.field input:user-invalid { border: 3px solid #b42318; }
.field:has(input:user-invalid) .error { display: block; }
.field:has(input:user-invalid) .error::after { content: attr(data-message); }
This pure CSS version has a limit, and it matters for assistive technology. Each field names its message element with aria-describedby, and a browser reads the text of a referenced element even when that element is hidden. That is why the words are not written inside the element: a hidden message in the page would be read on every field, valid or not. Here the description is empty while the field is valid, and holds the message while the field is :user-invalid, so a screen reader reads it when the person moves focus to the field. The member code field keeps its hint in both states. But nothing announces the message at the moment it appears, so a person who has not returned to the field is not told. The next two sections fix that.
Your own messages
To write your own words, ask the browser what is wrong. Each field has a validity object with a flag for every kind of problem: valueMissing, typeMismatch, patternMismatch, rangeUnderflow, rangeOverflow, badInput and others. Pick the message from the first flag that is true.
Put novalidate on the form, so that your script, and not the browser's bubble, shows the problems. Then each field must name its message element with aria-describedby, and the script sets aria-invalid on the field. Write messages as text with textContent.
An error summary and focus
When a form has several problems, list them all at the top and move focus to the list. A person who uses a screen reader or a keyboard hears what is wrong and can follow a link to each field. WCAG asks that an error found automatically is identified and described in text.
The summary here is a div with tabindex="-1", which lets a script focus it without adding it to the Tab order. Each message in the list is a link. The script moves focus to the field when the link is used, so the next keypress goes into the field. After the first failed attempt, each field is checked again as the visitor types, and its message disappears when the value is right.
HTML
<form class="form-custom" id="form-custom" novalidate aria-labelledby="form-custom-title">
<h2 class="form-custom__title" id="form-custom-title">Book seats</h2>
<div class="form-custom__summary" id="form-custom-summary" tabindex="-1" role="group" aria-labelledby="form-custom-summary-title" hidden>
<h3 class="form-custom__summary-title" id="form-custom-summary-title">There is a problem</h3>
<ul class="form-custom__summary-list" id="form-custom-summary-list"></ul>
</div>
<p class="form-custom__field">
<label for="form-custom-name">Name</label>
<input id="form-custom-name" name="name" type="text" autocomplete="name" required aria-describedby="form-custom-name-error">
<span class="form-custom__error" id="form-custom-name-error"></span>
</p>
<p class="form-custom__field">
<label for="form-custom-email">Email address</label>
<input id="form-custom-email" name="email" type="email" autocomplete="email" required aria-describedby="form-custom-email-error">
<span class="form-custom__error" id="form-custom-email-error"></span>
</p>
<p class="form-custom__field">
<label for="form-custom-seats">Seats (1 to 10)</label>
<input id="form-custom-seats" name="seats" type="number" inputmode="numeric" min="1" max="10" required aria-describedby="form-custom-seats-error">
<span class="form-custom__error" id="form-custom-seats-error"></span>
</p>
<p><button class="form-custom__submit" id="form-custom-submit">Book</button></p>
<p class="form-custom__status" id="form-custom-status" role="status"></p>
</form>CSS
.form-custom {
--fc-bg: #ffffff;
--fc-fg: #1b1f2a;
--fc-muted: #4a5163;
--fc-line: #6b7280;
--fc-accent: #3730a3;
--fc-on-accent: #ffffff;
--fc-bad: #b42318;
max-width: 26rem;
padding: 1rem;
color: var(--fc-fg);
background: var(--fc-bg);
}
.form-custom__title { margin: 0 0 1rem; font-size: 1.25rem; }
.form-custom__summary {
margin: 0 0 1rem;
padding: 0.75rem 1rem;
border: 3px solid var(--fc-bad);
border-radius: 6px;
}
.form-custom__summary[hidden] { display: none; }
.form-custom__summary-title { margin: 0 0 0.5rem; font-size: 1.0625rem; color: var(--fc-bad); }
.form-custom__summary-list { margin: 0; padding-inline-start: 1.25rem; }
.form-custom__summary a { color: var(--fc-fg); }
.form-custom__field { display: grid; gap: 0.25rem; margin: 0 0 1rem; }
.form-custom__field label { font-weight: 600; }
.form-custom__field input {
min-height: 44px;
padding: 0.25rem 0.5rem;
font: inherit;
color: var(--fc-fg);
background: var(--fc-bg);
border: 1px solid var(--fc-line);
border-radius: 6px;
}
.form-custom__field input[aria-invalid="true"] { border: 3px solid var(--fc-bad); }
.form-custom__error { color: var(--fc-bad); font-size: 0.9375rem; font-weight: 600; }
.form-custom__error:empty { display: none; }
.form-custom__field input:focus-visible,
.form-custom__summary:focus-visible,
.form-custom__summary a:focus-visible {
outline: 3px solid var(--fc-accent);
outline-offset: 2px;
}
.form-custom__submit {
min-height: 44px;
padding: 0.5rem 1.5rem;
font: inherit;
color: var(--fc-on-accent);
background: var(--fc-accent);
border: 1px solid var(--fc-accent);
border-radius: 8px;
cursor: pointer;
}
.form-custom__submit:focus-visible {
outline: 3px solid var(--fc-fg);
outline-offset: 2px;
}
.form-custom__status { margin: 0; min-height: 1.5em; color: var(--fc-muted); }
@media (prefers-color-scheme: dark) {
.form-custom {
--fc-bg: #12141c;
--fc-fg: #eceef5;
--fc-muted: #b6bccb;
--fc-line: #8b93a7;
--fc-accent: #b4b8ff;
--fc-on-accent: #12141c;
--fc-bad: #ff8a80;
}
}JavaScript
var form = document.getElementById('form-custom');
var summary = document.getElementById('form-custom-summary');
var summaryList = document.getElementById('form-custom-summary-list');
var statusLine = document.getElementById('form-custom-status');
var fields = Array.prototype.slice.call(form.querySelectorAll('input'));
// One message per kind of problem. The browser decides which kind applies (field.validity).
var MESSAGES = {
'form-custom-name': { valueMissing: 'Enter your name.' },
'form-custom-email': {
valueMissing: 'Enter your email address.',
typeMismatch: 'Enter an address in the form name@example.com.'
},
'form-custom-seats': {
valueMissing: 'Enter the number of seats.',
badInput: 'Enter a number, not text.',
rangeUnderflow: 'Book at least 1 seat.',
rangeOverflow: 'Book at most 10 seats.'
}
};
function messageFor(field) {
var kinds = MESSAGES[field.id];
for (var kind in kinds) {
if (field.validity[kind]) return kinds[kind];
}
return field.validity.valid ? '' : 'Check this value.';
}
function showError(field) {
var text = messageFor(field);
document.getElementById(field.id + '-error').textContent = text;
field.setAttribute('aria-invalid', text ? 'true' : 'false');
return text;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
statusLine.textContent = '';
summaryList.textContent = '';
fields.forEach(function (field) {
var text = showError(field);
if (!text) return;
var item = document.createElement('li');
var link = document.createElement('a');
link.href = '#' + field.id;
link.textContent = text;
item.appendChild(link);
summaryList.appendChild(item);
});
summary.hidden = summaryList.children.length === 0;
if (summaryList.children.length) {
summary.focus();
} else {
statusLine.textContent = 'Example only: every field is valid and nothing was sent.';
}
});
// A link in the summary moves focus to its field; a plain #fragment would only scroll.
summaryList.addEventListener('click', function (event) {
var link = event.target.closest('a');
if (!link) return;
event.preventDefault();
document.getElementById(link.getAttribute('href').slice(1)).focus();
});
// After the first attempt, each field is checked again as the visitor edits it.
form.addEventListener('input', function (event) {
if (event.target.getAttribute('aria-invalid') === 'true') showError(event.target);
});The same with XON
XON's validate part gives you messages and a summary from attributes. data-error-in="id" names the element that shows a field's message. data-errors-in="id" on the form names the element for the summary. data-message-required and similar attributes hold your words. data-rule adds rules the browser lacks, such as min-words:3. The part builds on the browser's own checks, so required and pattern keep working.
One detail comes from the layout. XON shows a field's message when the person leaves the field. If the message is added below the field and no room was kept for it, the Send button moves down. A click that starts before the move and ends after it is then lost, because the button is no longer under the pointer. Reserve space for the message in the layout, so that nothing moves when it appears. The example does this, and its check confirms that the button does not move.
HTML
<form class="form-xon" id="form-xon" aria-labelledby="form-xon-title" data-errors-in="form-xon-summary" data-on-submit="sendExample">
<h2 class="form-xon__title" id="form-xon-title">Send a note</h2>
<div class="form-xon__summary" id="form-xon-summary" hidden></div>
<p class="form-xon__field">
<label for="form-xon-name">Name</label>
<input id="form-xon-name" name="name" type="text" autocomplete="name" required data-message-required="Enter your name" data-error-in="form-xon-name-error">
<span class="form-xon__error" id="form-xon-name-error"></span>
</p>
<p class="form-xon__field">
<label for="form-xon-note">Note (at least 3 words)</label>
<textarea id="form-xon-note" name="note" rows="3" required data-rule="min-words:3" data-message-required="Write a note" data-message-min-words="Write at least three words" data-error-in="form-xon-note-error"></textarea>
<span class="form-xon__error" id="form-xon-note-error"></span>
</p>
<p><button class="form-xon__submit" id="form-xon-submit">Send</button></p>
<p class="form-xon__status" id="form-xon-status" role="status" data-text="note.status"></p>
</form>CSS
.form-xon {
--fx-bg: #ffffff;
--fx-fg: #1b1f2a;
--fx-muted: #4a5163;
--fx-line: #6b7280;
--fx-accent: #3730a3;
--fx-on-accent: #ffffff;
--fx-bad: #b42318;
max-width: 26rem;
padding: 1rem;
color: var(--fx-fg);
background: var(--fx-bg);
}
.form-xon__title { margin: 0 0 1rem; font-size: 1.25rem; }
.form-xon__summary {
margin: 0 0 1rem;
padding: 0.75rem 1rem;
border: 3px solid var(--fx-bad);
border-radius: 6px;
}
.form-xon__summary[hidden] { display: none; }
.form-xon__summary h2 { margin: 0 0 0.5rem; font-size: 1.0625rem; color: var(--fx-bad); }
.form-xon__summary ul { margin: 0; padding-inline-start: 1.25rem; }
.form-xon__summary a { color: var(--fx-fg); }
.form-xon__field { display: grid; gap: 0.25rem; margin: 0 0 1rem; }
.form-xon__field label { font-weight: 600; }
.form-xon__field input,
.form-xon__field textarea {
min-height: 44px;
padding: 0.25rem 0.5rem;
font: inherit;
color: var(--fx-fg);
background: var(--fx-bg);
border: 1px solid var(--fx-line);
border-radius: 6px;
}
.form-xon__field input[aria-invalid="true"],
.form-xon__field textarea[aria-invalid="true"] {
border-color: var(--fx-bad);
box-shadow: inset 0 0 0 2px var(--fx-bad); /* thicker without changing the size of the box */
}
.form-xon__error { color: var(--fx-bad); font-size: 0.9375rem; font-weight: 600; }
.form-xon__error { display: block; min-height: 1.5em; } /* room is kept for the message, so the button never jumps */
.form-xon__field input:focus-visible,
.form-xon__field textarea:focus-visible,
.form-xon__summary:focus-visible,
.form-xon__summary a:focus-visible {
outline: 3px solid var(--fx-accent);
outline-offset: 2px;
}
.form-xon__submit {
min-height: 44px;
padding: 0.5rem 1.5rem;
font: inherit;
color: var(--fx-on-accent);
background: var(--fx-accent);
border: 1px solid var(--fx-accent);
border-radius: 8px;
cursor: pointer;
}
.form-xon__submit:focus-visible {
outline: 3px solid var(--fx-fg);
outline-offset: 2px;
}
.form-xon__status { margin: 0; min-height: 1.5em; color: var(--fx-muted); }
@media (prefers-color-scheme: dark) {
.form-xon {
--fx-bg: #12141c;
--fx-fg: #eceef5;
--fx-muted: #b6bccb;
--fx-line: #8b93a7;
--fx-accent: #b4b8ff;
--fx-on-accent: #12141c;
--fx-bad: #ff8a80;
}
}JavaScript
var note = xon.data('note', { status: '' });
// The validate part has already checked the form when this runs, because an invalid
// form is never sent. The preview cannot send anything, so the example stops here.
function sendExample(event) {
event.preventDefault();
note.status = 'Example only: the form is valid and nothing was sent.';
}
xon.use(sendExample);What the browser cannot do for you
Checks in the browser help the person filling in the form. They protect nothing: anyone can send a request without your page, so the server must check every value again.
The HTML Standard says the same in its own words: servers should not rely on client-side validation, because it can be bypassed on purpose or by tools that do not implement it. Treat everything in this tutorial as help for the person. Your server decides what it accepts.
All examples on this page passed their checks in Chrome 143 on 3 December 2026. They were not tested in other browsers.
References
- MDN: Client-side form validation (read on 3 December 2026)
- MDN: the pattern attribute (read on 3 December 2026)
- MDN: :user-invalid (read on 3 December 2026)
- MDN: ValidityState (read on 3 December 2026)
- MDN: aria-describedby (read on 3 December 2026)
- W3C: Accessible Name and Description Computation 1.2, steps 2A and 2F (read on 3 December 2026)
- W3C: Understanding Success Criterion 3.3.1, Error Identification (read on 3 December 2026)
- HTML Standard: form control infrastructure, security of client-side validation (read on 3 December 2026)
- XON documentation: form rules, messages and steps (read on 3 December 2026)
Snippets that go with this tutorial
These snippets in the gallery use the same techniques: