Sub topic 5
How the browser reports errors and when to use novalidate
This chapter covers what the browser does when a user submits a form, where it shows messages, and how to switch that behavior off or replace it. It assumes you know the constraint attributes from the earlier chapters (required, minlength, pattern and so on), basic event handling, and how a form submission reaches a server.
What happens when the user submits
When a form is submitted, the browser runs interactive validation before anything is sent. It checks every control that takes part in validation against its constraints. Only then does it decide whether the submission can continue.
The steps are:
- The user clicks a submit button, presses Enter in a text field, or your code calls
form.requestSubmit(). - The browser collects the controls that are subject to validation.
- If every control is valid, the
submitevent fires and the form is sent unless a handler cancels it. - If any control is invalid, the browser fires an
invalidevent at each invalid control in document order. It does not firesubmit. - If no
invalidhandler canceled its event, the browser focuses the first invalid control and shows a message next to it.
An invalid form never reaches your submit handler. If you attach validation logic only to submit, it will not run for forms that the browser already rejects. This is the most common source of confusion when people first mix built-in validation with their own code.
Where the message comes from
The text in the browser's error bubble comes from the browser, not from your page. Four things follow from that.
- The wording differs between browsers and changes between versions.
- The language follows the browser's interface language, not the
langattribute of your page. - You cannot style the bubble with CSS.
- Most browsers show one message at a time, for the first invalid control only.
For a failed pattern, the browser usually appends the title attribute to its generic message, so a good title describes the format in words. For other failures, the message is available as the control's validationMessage property, which you can read and reuse in your own UI.
Which controls are checked
A control that is subject to validation has willValidate set to true. These controls are skipped:
- Disabled controls.
readonlyinputs, because the user cannot change them.type="hidden"inputs.- Buttons whose type is
buttonorreset. - Controls inside a
<datalist>.
An empty value passes every constraint except required. A blank optional email field is valid, and pattern or minlength is never applied to it.
Which submissions are validated
Not every way of submitting a form triggers validation.
| Action | Validated? | `submit` event fires? |
|---|---|---|
| Click a submit button | Yes | Only if the form is valid |
| Press Enter in a text field | Yes | Only if the form is valid |
| `form.requestSubmit()` | Yes | Only if the form is valid |
| `form.submit()` | No | No |
| Click a button with `formnovalidate` | No | Yes |
| Any submission of a form with `novalidate` | No | Yes |
form.submit() skips both validation and the submit event. If your code calls it after its own checks, nothing else protects the data. Use requestSubmit() when you want a scripted submission to behave like a click on the submit button.
Pressing Enter acts as a click on the form's default button, which is the first submit button in document order. If that button has formnovalidate, pressing Enter also skips validation. Put "Save draft" buttons after the main submit button.
Turning validation off: novalidate and formnovalidate
The novalidate attribute on a <form> disables interactive validation for the whole form. The formnovalidate attribute on a submit button disables it for submissions made with that button only.
<form action="/profile" method="post" novalidate>
<!-- every submission skips interactive validation -->
</form>
<form action="/profile" method="post">
<button type="submit">Save</button>
<button type="submit" formaction="/profile/draft" formnovalidate>Save draft</button>
</form>In script, form.noValidate = true has the same effect as the attribute.
These switches turn off only the submit-time check and the bubble. Everything else keeps working:
- Constraints are still evaluated, and
:invalidand:validstill match. validity,validationMessage,checkValidity()andreportValidity()still return real answers.- Browser input types such as
type="number"still sanitize or reject values the same way.
That is why novalidate is usually the first step toward custom error UI. You keep the browser's rule engine and replace only its presentation.
Checking validity from script
Three methods let you run validation yourself.
| Method | Fires `invalid` events | Shows browser UI | Returns |
|---|---|---|---|
| `checkValidity()` | Yes | No | `true` or `false` |
| `reportValidity()` | Yes | Yes, unless canceled | `true` or `false` |
| `requestSubmit()` | Yes, if validating | Yes, unless canceled | nothing |
checkValidity() is not a silent check. It still fires invalid events, so a handler that writes error text will run. If you only need to know whether a field is valid without side effects, read field.validity.valid.
You can call these methods on a single control or on the whole form. On a form, checkValidity() returns true only if every control is valid.
Replacing the bubble without novalidate
You do not have to disable validation to control how errors appear. The invalid event is cancelable. If you call preventDefault() on it, the browser blocks the submission but does not show its bubble. You then show the message yourself.
The invalid event does not bubble, so you listen on each control rather than on the form. Because canceling also stops the browser from moving focus, your handler must do that itself.
This page is a complete example. It also has a "Save draft" button that skips validation.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom error reporting</title>
</head>
<body>
<form id="profile" action="/profile" method="post">
<label for="name">Name</label>
<input id="name" name="name" required minlength="2">
<p id="name-error"></p>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<p id="email-error"></p>
<button type="submit">Save</button>
<button type="submit" formaction="/profile/draft" formnovalidate>Save draft</button>
</form>
<script>
const form = document.getElementById('profile');
for (const field of form.querySelectorAll('input')) {
const error = document.getElementById(`${field.id}-error`);
field.addEventListener('invalid', (event) => {
event.preventDefault();
error.textContent = field.validationMessage;
if (field === form.querySelector('input:invalid')) {
field.focus();
}
});
field.addEventListener('input', () => {
if (field.validity.valid) error.textContent = '';
});
}
</script>
</body>
</html>The invalid handler runs once per invalid field during a submit attempt. The input handler clears a message as soon as the user fixes the value. The check form.querySelector('input:invalid') returns the first invalid input in document order, so exactly one field receives focus.
This approach keeps the form working if your script fails to load, because the browser's default behavior remains in place. With novalidate, a script failure leaves the form with no client-side checks at all.
Choosing between the options
| Situation | Suggested approach |
|---|---|
| Simple form, default look is acceptable | Keep default validation |
| You want your own message text or placement, and the form should still work without JavaScript | Cancel `invalid` events as above |
| You want all errors listed at once, or a summary at the top of the form | `novalidate` plus a `submit` handler |
| A button must submit incomplete data (draft, back, cancel) | `formnovalidate` on that button |
| Multi-step form where hidden steps contain required fields | Validate the visible step yourself, or remove the hidden fields from validation |
A novalidate form makes your script responsible for blocking the submission. If your submit handler throws an error before it calls preventDefault(), the invalid data goes to the server.
Gotchas
- Hidden required fields block silently. A required control inside a
display: nonepanel cannot receive focus. Chrome logs "An invalid form control is not focusable" and the form does not submit, with no visible message. Disable such controls, removerequiredwhile they are hidden, or usenovalidateand handle the case yourself. - Only the first error shows. With default validation, users fix one field and submit again to see the next. A custom
submithandler can show all errors at once. submitlisteners miss invalid forms. Code that logs, tracks, or disables the button onsubmitnever runs when the browser blocks the submission. Useinvalidor a buttonclickhandler if you need to observe failed attempts.- Per-button
formnovalidateaffects Enter. See the default button rule above. - Client checks are optional for an attacker. Anyone can send a request without a browser, so
novalidateor its absence changes nothing about what the server must verify.
Summary of the working model
- Validation runs before the
submitevent, and a failed check suppresses that event. - The
invalidevent is cancelable and does not bubble. Canceling it removes the browser's bubble and focus movement. novalidateandformnovalidateremove only the submit-time gate. The rules, the API, and the CSS pseudo-classes keep working.checkValidity()firesinvalidevents without UI.reportValidity()fires them and shows UI.form.submit()bypasses everything. PreferrequestSubmit().
Exercise
A form has no novalidate attribute. A required email field is empty, and a script listens for submit on the form to show an error summary. A user clicks the submit button. Does the script's handler run, and what should you listen for instead if you want to react to this failed attempt?
Show answer
The handler does not run. The browser finds the empty required field, fires invalid on it, and suppresses the submit event. To react to the failed attempt, listen for invalid on each control (the event does not bubble, so a listener on the form would only see it in the capture phase), or add novalidate so that submit fires and the handler can run its own checks.
Exercise
Your "Save draft" button submits to a different URL and must accept incomplete data, but the main "Save" button must still be validated. Which attribute do you use, where do you put it, and what happens if that button comes first in the markup and the user presses Enter in a text field?
Show answer
Put formnovalidate on the "Save draft" button, and formaction for the different URL. Only submissions made with that button skip validation. If the button comes first, it is the form's default button, so pressing Enter acts as a click on it and the form is submitted without validation. Place "Save" first in the markup to avoid this.