HTML5 Form Validation with Constraint API

In this tutorial we’re going to take a look at some basic front-end form validation techniques. These techniques in no way replace the need for back-end validation, but they are useful for providing visual queues for how to complete your forms.


Front-end validation isn’t about stopping errors, its about preventing them. Let’s provide some interactive visual queues to our user to prevent them from making errors in the first place. This is especially helpful in forms where specific data is needed.

See the Pen HTML5 Validation with Lasers by Kevin Chappell (@kevinchappell) on CodePen.

Custom Messaging

Browsers that support the Constraint API include messaging that informs the user of issues however these messages can sometimes be vague. For example we may have required fields for password and password confirmation and the browser will provide a message stating they are required if the user submits the form without filling the fields, but what happens if the passwords don’t match? Is there a way to check for a match and use the browser’s standard notification method to inform the user their passwords don’t match? You bet.

See the Pen HTML5 Constraint API – Password check by Kevin Chappell (@kevinchappell) on CodePen.

In the first part of the above example you’ll notice we are also enforcing password policy with the input pattern. The second part we add an event listener to the keyup event and have a callback that checks that the passwords match. The prevents the user from submitting the form, only to have it reload and be told they’ve made a mistake.


The built-in error notifications of most browsers are convenient but the styling could use a little work. Unfortunately there is currently no way to modify the built-in notifications. Mozilla browsers have x-moz-errormessage selector and Chrome had ::-webkit-validation-bubble-* but the Mozilla selector is poorly supported and the Chrome selector no longer exists. If you want to change the style of the built-in notifications you’ll need the replace them altogether and while not difficult, could be time consuming. TJ Van Toll has a good write-up on this but essentially you addEventListener to the “invalid” bubble event, prevent it from continuing and replace it with your own.


Use the Constraint API. While not a replacement for backend validation it’s good practice and user experience.

Leave a Reply

Your email address will not be published. Required fields are marked *