Instant Form Validation Using JavaScript

HTML5 introduces a couple of new attributes for implementing browser-based form validation. The pattern attribute is a regular-expression that defines the range of valid inputs for textarea elements and most types of input. The required attribute specifies whether a field is required. For legacy browsers that don’t implement these attributes, we can use their values as the basis of a polyfill. We can also use them to provide a more interesting enhancement – instant form validation.
We have to be very careful here not to get carried away, creating overly aggressive validation that breaks the natural browsing behavior and gets in people’s way. For example, I’ve seen forms where it’s impossible to Tab away from an invalid field – JavaScript is used (or rather abused) to force the focus to stay inside the field until it’s valid. This is very poor usability, and directly contravenes accessibility guidelines.
What we’re going to do in this article is far less intrusive. It’s not even full client-side validation – it’s just a subtle usability enhancement, implemented in an accessible way, which (as I discovered while testing the script) is almost identical to something that Firefox now does natively!
The Basic Concept
In recent versions of Firefox, if a required field is empty or its value doesn’t match the pattern then the field will show a red outline, as illustrated by the following figure.

This doesn’t happen straight away of course. If it did, then every required field would have that outline by default. Instead, these outlines are only shown after you’ve interacted with the field, which is basically (though not precisely) analogous to the onchange event.
So that’s what we’re going to do, using onchange as the triggering event. As an alternative, we could use the oninput event, which fires as soon as any value is typed or pasted into the field. But this is really too instant, as it could easily be triggered on and off many types in rapid succession while typing, creating a flashing effect which would be annoying or impossibly distracting for some users. And, in any case, oninput doesn’t fire from programmatic input, which onchange does, and we might need that to handle things like auto-complete from third-party add-ons.
Defining the HTML and CSS
So let’s have a look at our implementation, starting with the HTML it’s based on: