# Errors after you type

Source: https://websgeek.com/html-form-validation-not-working
Publisher: WebsGeek (https://websgeek.com), updated 2026-11-25

You will see why native form validation shows errors too early, skips some submits, gets stuck or ignores a pattern, and you will read the browser's own verdict live while each one happens.

## Read the browser's verdict

When HTML form validation seems not to work, the browser has almost always run the check and reached a different verdict than you expected. Four causes cover most cases: `:invalid` styles fire before anyone types, `form.submit()` skips validation entirely, a `setCustomValidity()` message was never cleared, or a `pattern` failed to compile and is being ignored. Every field exposes its verdict in `field.validity`, so you can read the decision instead of guessing.

Start by watching that verdict. Each pill below is one property of the field's `ValidityState`. A filled pill means it is true right now.

> Interactive demo: Watch the verdict change as you type (try it on the page).

Type `abc-123` and `patternMismatch` lights up. Delete everything and `valueMissing` takes over, because a pattern only judges a value that is not empty. In Quantity, try `0`, `11` and `2.5` to see `rangeUnderflow`, `rangeOverflow` and `stepMismatch`. Then type `1e`, and try `--1` too. The readout shows `value ""` and the `badInput` pill lights up. Your browser could not turn the text into a number, so it reports `badInput` and hands your script an empty string. Code that reads `field.value` sees nothing at all. Which half-typed strings count as bad input is the browser's call, so the pills show what yours decided.

Now switch on **readonly**. `willValidate` turns off and `checkValidity()` returns `true`, even with both fields empty. Controls that are **barred from constraint validation** are not checked at all. This includes `readonly` and `disabled` fields, `input type="hidden"`, and buttons that are not submit buttons (`type="reset"` and `type="button"`, including `input type="button"` and `input type="reset"`). Other cases exist too: `output`, `fieldset` and `object` elements, and controls inside a `datalist`. A submit button is not barred: its `willValidate` is `true`, and it can even carry `setCustomValidity()`. A required field that a script disables "to prevent edits" will never stop a submit.

**One level deeper.** `validity` is a live object. Each flag is recalculated from the current value and attributes whenever you read it, and `valid` simply means no other flag is true. `checkValidity()` reads that answer and fires an `invalid` event when it fails. `reportValidity()` does the same and also shows the browser's message bubble. Nothing on the page changes until something asks: a CSS selector, a submit or your code.

**Ask any field why it is invalid.**

```
function why(field) {
  if (!field.willValidate) return 'skipped: barred from validation';
  const failed = [];
  for (const key in field.validity) {
    if (key !== 'valid' && field.validity[key]) failed.push(key);
  }
  return failed.length
    ? `${failed.join(', ')}: ${field.validationMessage}`
    : 'valid';
}

// In the console: [...form.elements].map(why)
// The submit button is listed too, as 'valid'.
```

Run that over `form.elements` and the form's submit button shows up as `valid`. That is correct: it takes part in validation and simply has nothing to fail.

## Red before anyone types

The most common complaint is not that validation fails to run. It is that it runs too early. `:invalid` matches any field that fails its constraints right now, and an empty required field fails as soon as the page loads.

> Interactive demo: Same field, two selectors (try it on the page).

The left lane is red before you touch it, and its readout says when: at page load. In the right lane, type a partial address such as `ada@`. It stays calm while you type. Press Tab and it turns red. Go back and finish the address. The error clears on the keystroke that fixes it, without waiting for another blur. That is the timing most people expect from a form, and it costs one selector.

Now press **Reset**, then **Try to submit** without typing. Both lanes go red, because a submit attempt counts as interaction for every field in the form. Fill both with valid addresses and submit again: the readouts report that the form is valid and would be sent. Tabbing through the right field without typing should leave it clear: the browser waits for a changed value. The readouts record what your browser actually did, including whether it supports `:user-invalid` at all.

**One level deeper.** Each field carries a hidden **user validity** flag that starts as false. The HTML spec sets it to true when the user changes the value and commits it, which for a text field means leaving it. It also sets it on every field in the form when a submit is attempted, and that step runs before the browser checks `novalidate`. `:user-invalid` is `:invalid` plus that flag. `form.reset()` sets the flag back to false. Scripts cannot read the flag directly, so these readouts call `field.matches(':user-invalid')`.

`:user-invalid` and `:user-valid` work in Chrome and Edge 119+, Firefox 88+ and Safari 16.5+. The readouts above still test your own browser: they say "not supported" when the selector does not parse. A selector list that contains an unsupported selector drops the whole rule, so give `:user-invalid` its own rule.

**Swap one selector to fix the timing.**

```
/* Red only after the user commits a value or tries to submit */
input:user-invalid {
  border-color: var(--error);
}
input:user-invalid + .hint {
  color: var(--error);
}

/* Avoid: paints every empty required field red at page load */
input:invalid {
  border-color: var(--error);
}
```

## Not every submit checks

A form can be sent in several ways, and they do not all validate. The email field below is required and starts empty. Try each path and read the event order in the readout.

> Interactive demo: Five ways to send one form, and two ways to fail (try it on the page).

The **Submit** button and `requestSubmit()` behave the same way: one `invalid` event, no `submit` event, nothing sent, and the browser's message appears. Pressing Enter in the field does the same, because it clicks the form's default button for you.

Press **form.reset()**, then **form.submit()**. No events fire at all, and the empty form is sent. Your own `submit` listener never runs, so any `fetch()` or `preventDefault()` inside it is skipped too. Read the `:user-invalid` part of the readout: it says `no`, because the browser never treated the call as a submit attempt.

Now press **form.reset()** again and switch on **novalidate**, or use **Save draft**. The `submit` event fires and the form is sent with no `invalid` event. Check the `:user-invalid` part of the readout once more. The spec marks fields as interacted with before it looks at `novalidate`, so this path should flip it to `yes`, and the readout shows what your browser really did. `requestSubmit(draftButton)` respects that button's `formnovalidate`, which is how a script should send a draft without validating.

The last two buttons pass `requestSubmit()` a bad submitter. A button that is not a submit button throws a `TypeError`. A real submit button that belongs to a different form throws a `NotFoundError`. The readout prints the exception name, so you can tell the two apart.

**One level deeper.** Every path runs the same form submission algorithm. `form.submit()` enters it with a flag that skips the middle part: no user validity update, no constraint check and no `submit` event. Every other path goes through those steps in order. The browser marks the fields as interacted with and validates them, unless the submitter or the form has `novalidate`. It fires `invalid` on each failing field and reports the problem, usually by focusing the first failing field. Only then does it fire `submit`. The `invalid` event does not bubble, so a listener on the form only hears it in the capture phase.

**Send from script without losing validation.**

```
// Skips validation, the submit event and your handlers:
form.submit();

// Behaves like a click on the default submit button:
form.requestSubmit();

// As if this button was pressed (its formnovalidate is respected):
form.requestSubmit(saveDraftButton);

// Throws TypeError: not a submit button.
// Throws NotFoundError: a submit button of another form.

// invalid does not bubble, so listen in the capture phase:
form.addEventListener('invalid', event => {
  event.target.setAttribute('aria-invalid', 'true');
}, true);
```

## The error that never leaves

`setCustomValidity(message)` adds a rule the browser does not know, such as "the two emails must match". Any non-empty string marks the field invalid and sets `customError`. The browser never clears it for you. The field stays invalid until your code calls `setCustomValidity('')`.

> Interactive demo: Type a different email, then fix it (try it on the page).

Type `ada@` into both Repeat fields, then finish the address so it matches. The right lane clears. The left lane stays red, and its readout says **stuck**: the values match, but `customError` is still true. In a real form, that field would block every submit with a message that is no longer true.

The bug usually hides in one of three places. The message is set in a branch with no `else`. It is set inside an `invalid` or `submit` handler that does not run again after the fix. Or it is set on one field but only re-checked when that field changes, not when its partner does. The fix is the same for all three: re-check on every input to either field, and always pass a string, an empty one when the rule passes.

**Always pass a string, empty when the rule passes.**

```
const email = form.elements.email;
const repeat = form.elements.repeat;

function checkMatch() {
  const differ = repeat.value !== '' && repeat.value !== email.value;
  repeat.setCustomValidity(differ ? 'The emails do not match.' : '');
}

email.addEventListener('input', checkMatch);
repeat.addEventListener('input', checkMatch);
```

> **Only an empty string clears it.** `setCustomValidity(null)` and `setCustomValidity(undefined)` turn their argument into the strings "null" and "undefined". They set an error instead of removing one.

## A pattern your browser ignores

Sometimes validation does nothing at all, and any value passes. If the field has a `pattern`, check the pattern itself. The HTML standard compiles it as `^(?:your pattern)$` with the regular expression `v` flag, which is stricter than the older `u` flag. If the pattern fails to compile, the browser ignores the attribute and the field accepts anything. Chrome logs a console warning, and the page itself gets no signal at all.

> Interactive demo: Edit the pattern, then the value (try it on the page).

For years, `[a-z-]+` was a correct pattern. Under the `v` flag, a bare hyphen inside a character class is a syntax error, so the field lets `HELLO WORLD` through and never turns red. Press **Escape the hyphen** and it turns red at once. Inside a character class, the `v` flag also requires you to escape `( ) [ ] { } / | \ -`, and it rejects doubled punctuation such as `&&` or `--`. Try typing one into the pattern box.

Browsers that compile `pattern` with the `v` flag: Chrome since 2023, Firefox 116+ and Safari 17+. The note under the demo is the proof for your own browser. It builds a hidden field with `pattern="[a-z-]"`, gives it the value `Z`, and reports whether your browser ignored the pattern.

**Test a pattern the way the browser compiles it.**

```
function checkPattern(pattern) {
  try {
    new RegExp(`^(?:${pattern})$`, 'v');
    return 'ok';
  } catch (error) {
    return `ignored by the browser: ${error.message}`;
  }
}

checkPattern('[a-z-]+');   // ignored
checkPattern('[a-z\\-]+'); // ok (one backslash in the HTML attribute)
```

## Your messages, native timing

The browser's message bubble cannot be styled. You cannot control its wording, placement or how long it stays. Many teams therefore add `novalidate` and show their own messages. You do not have to give up the browser's rules to do that. Keep `required`, `type` and `pattern` in the HTML as the single source of truth, and let a script decide only **when** to show the result.

> Interactive demo: Tune when the error appears (try it on the page).

With both switches on, you get the same timing as `:user-invalid`. The field stays quiet while you type, shows an error once it loses focus, then updates live until the value is fixed. Turn off **Wait for blur** to feel the alternative: the error appears on the first keystroke, while the address is still half written. Turn off **Live updates** and the old message stays after you fix the value, until you leave the field again. The code under the demo changes with your switches. It expects `novalidate` on the form and, on each field you want a message for, an `aria-describedby` with one id that points at its message element. Controls without one, such as the submit button, are skipped.

The text comes from `validationMessage`, so it is already in the browser's language. `aria-invalid` tells assistive technology that the field has an error, and `aria-describedby` makes screen readers read the message when the field gets focus. When a submit fails, the script moves focus to the first invalid field, as the browser does natively. The readout also reports `:user-invalid`. The spec marks fields as interacted with on any submit attempt, even when the form has `novalidate`, so your CSS can keep using the selector. The readout shows whether your browser follows that rule.

## When to trust it

Native constraint validation is the right default for most forms. It is fast and localized. It works before your JavaScript loads, and it gives you a precise, live verdict through `validity`. Most cases of form validation "not working" are timing or wiring problems, not missing features. When something looks wrong, read the verdict before you rewrite anything.

> **Debug in this order.** 1. Log `field.validity` and `willValidate`. 2. Check that the styles use `:user-invalid`, not `:invalid`. 3. Search for `.submit()` and replace it with `requestSubmit()`. 4. Find every `setCustomValidity` and make sure it can receive `''`. 5. Run each `pattern` through `new RegExp(..., 'v')`.

Use the native rules for anything you can express as an attribute. Style with `:user-invalid`. Send from script with `requestSubmit()`. Add cross-field rules with `setCustomValidity`, re-checked on every input. When you need styled, accessible messages, use the pattern from section 6. Keep the attributes, add `novalidate`, and show `validationMessage` with `aria-invalid` and `aria-describedby`. After a successful submit, confirm it visibly, as in [a save you can see land](https://websgeek.com/a-save-you-can-see-land).

Do not treat it as security. Anyone can remove `required` in dev tools, so the server must validate again. Do not use it for checks that need the network, such as "this username is taken". Run those in your submit handler, or [debounce](https://websgeek.com/debounce-vs-throttle) them while the user types. Do not call `form.submit()` unless you really mean to skip every check and every listener. If you add motion to errors, such as a shake, turn it off under `prefers-reduced-motion: reduce`. A red border and a clear sentence carry the message on their own.

## Quick answers

**Why is my HTML form validation not working?**
The browser has almost always run the check and reached a different verdict than you expected. Four causes cover most cases: :invalid styles firing before anyone types, form.submit() skipping validation, a setCustomValidity() message that was never cleared, or a pattern that failed to compile and is ignored. Read field.validity to see the actual verdict.

**Why does form.submit() skip HTML validation?**
Calling form.submit() enters the submission algorithm with a flag that skips the constraint check, the invalid events and the submit event. Your submit listeners never run, so a fetch() or preventDefault() inside them is skipped too. Use form.requestSubmit() instead, which validates like a click on the submit button.

**Why is my input red before I type anything?**
The :invalid selector matches any field that fails its constraints right now, and an empty required field fails at page load. Use :user-invalid instead. It matches only after the user commits a changed value or tries to submit. It works in Chrome and Edge 119+, Firefox 88+ and Safari 16.5+. The live readouts in this article still test your own browser.

**Why does setCustomValidity keep my field invalid?**
Any non-empty string passed to setCustomValidity() marks the field invalid, and the browser never clears it for you. Call setCustomValidity('') whenever the rule passes, and re-check on every input event of every field involved. Passing null or undefined does not clear it, because they become the strings "null" and "undefined".

**Why does my pattern attribute accept any value?**
If the pattern fails to compile, the browser ignores it and the field accepts anything. The HTML standard compiles it as ^(?:pattern)$ with the regular expression v flag, which browsers apply in Chrome since 2023, Firefox 116+ and Safari 17+. Under that flag, a bare hyphen in a character class such as [a-z-]+ is a syntax error, so escape it. You can test with new RegExp(..., 'v').

---
This is the text version of "Errors after you type" from WebsGeek. The original page has live, interactive demos: https://websgeek.com/html-form-validation-not-working
When you use or quote this, cite: Errors after you type, WebsGeek, https://websgeek.com/html-form-validation-not-working
