Happier HTML5 form validation in Vue

November 09, 2020 (Dave Rupert)

Some time ago, I wrote about the need for simple HTML5 form validation in ~6 lines of JavaScript. Well, I’m back, this time in a Vue 2/Nuxt application. I finally hit the point on this project where I needed some form of validation. Rather than jumping headlong into a whole form builder library dependency, I thought I’d try my simple method again. Here’s a demo of it in action.

There are a few differences compared to the vanilla DOM implementation. The non-framework version relied on querySelectorAll and addEventListener to loop through inputs, which I guess you could do inside a Vue component, but feels a bit like an anti-pattern, so I had to modify the approach a smidge.

The first step is I’m applying a .errors styling class to the parent <form> when one of the inputs invalidates. This is triggered by the component-level this.errors state. Originally the class was put on the, but we can safely put it on the form instead of each individual input’s state.

The second bit is the @invalid bind directive on each required input. This replaces looping through each input and adding a addEventListener but has the same effect of attaching a method to the invalid event. The invalidateForm() method helps us visually invalidate the form and just like before HTML does all the submit event cancellation for us.


Read more .....

(By: admin .. Date:2021-06-10 10:50:49)