Happier HTML5 form validation in Vue

Avatar of Chris Coyier
Chris Coyier on

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

It’s kind of neat that we can do input:invalid {} in CSS to style an input when it’s in an invalid state. Yet, used exactly like that, the UX is pretty bad. Say you have <input type="text" required>. That’s immediately invalid before the user has done anything. That’s such a bummer UX that you never see it used in the wild. But if we could just avoid that one thing, that :invalid selector can do a ton of work for us in form validation without needing to lean on a big fancy library.

Dave has an idea that’s a variation on the original 2017 idea.

It’s basically:

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

Now you’re only conditionally applying those native error styles when you’ve determined the form to be in an error state and added a class. And fortunately, testing that is pretty easy too. We could apply that class when the submit button is clicked:

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

Or you could do it when an input blurs or something. You could even wrap each input set in a wrapper and toggle the class on the wrapper when appropriate. The commented out code here could get you going there…

Dave kicked this idea over to Vue:

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.

Not using any library (on top of what you already use) is pretty sweet. HTML form validation is pretty much there. Here’s a fork of Dave’s where error messaging is revealed as well:

Direct Link →