Have the browser enforce matching registration passwords for you

When you're doing a registration form, it's common to have two password fields and require the user to enter their password twice so that they don't make a mistake.

This then requires something to check that both were entered identically. Of course, you'll do this on the server, but it's handy to have it on the client too.

That's relatively easy with JavaScript, but then you have the issue of where to display the "these don't match" error. The browser can, and does, display validity errors in forms if you set particular input types ("email") or validation rules. Perhaps we can put that to work for us?

Indeed we can. When the value of the first password field changes, we set the validity constraint on the second password field to be a regular expression which matches only exactly what was typed into the first password field. And then the browser handles all the validation for us; we set the message for errors with setCustomValidity and it's all good. Give it a try below, and Edit in JSBin to see how it works.

Example signup form