The trouble with :invalid on its own

Styling inputs via input:invalid {} is a genuine capability of CSS, but the naive application produces poor UX. An <input type="text" required> matches the selector the moment it renders, before the user has typed a character. That eagerness is why the pattern rarely appears in production. The fix is to decouple the styling from the pseudo-class and apply it only once the form is known to be in an error state.

Gating native error styles behind a class

Dave's approach, a variation on his original 2017 idea, conditionally scopes the native error styles:

form.errors :invalid {
  outline: 2px solid red;
}

Nothing renders as invalid until the error class is present. The decision of when that happens is straightforward to test — for instance, on submit button click:

submitButton.addEventListener("click", (e) => {
  form.classList.toggle("errors", !form.checkValidity())
});

Blur on an input is another reasonable trigger. A third option is wrapping each input group in a container and toggling the class on that wrapper, as the commented-out code above sketches out.

Porting the pattern to Vue

Dave translated the idea into a Vue form component.

We initialize the form component with errors: false because we don’t want the error styling until the user has submitted the form. The invalidateForm function just sets this.error = true. That’s one problem with the CSS :invalid pseudo class, it’s way too eager. Hooking into the invalid events, delays the styling until after the first form submission attempt and we know the form has errors.

The component therefore listens for invalid events rather than relying on the selector alone, which defers the styling until after the first submission attempt confirms errors exist. The upside is that it layers onto the stack you already run, with no additional validation library. An extended fork of Dave's version also reveals error messaging alongside the styling.