javascript 32 lines · 6 steps

Live password-match validation in the DOM

Two password fields are checked against each other on every keystroke, driving native validity, ARIA state, and the submit button.

Explained by highlit
1const form = document.querySelector('#signup-form');
2const password = form.querySelector('#password');
3const confirm = form.querySelector('#confirm-password');
4const submit = form.querySelector('button[type="submit"]');
5const feedback = form.querySelector('#confirm-feedback');
6 
7function validateMatch() {
8 const a = password.value;
9 const b = confirm.value;
10 
11 if (b.length === 0) {
12 confirm.setCustomValidity('');
13 feedback.textContent = '';
14 submit.disabled = a.length === 0;
15 return;
16 }
17 
18 if (a !== b) {
19 confirm.setCustomValidity('Passwords do not match');
20 confirm.setAttribute('aria-invalid', 'true');
21 feedback.textContent = 'Passwords do not match';
22 submit.disabled = true;
23 } else {
24 confirm.setCustomValidity('');
25 confirm.removeAttribute('aria-invalid');
26 feedback.textContent = 'Passwords match';
27 submit.disabled = a.length === 0;
28 }
29}
30 
31password.addEventListener('input', validateMatch);
32confirm.addEventListener('input', validateMatch);
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The Constraint Validation API lets you block native form submission by setting a custom validity message on a field.
  2. 2Mirroring validation state into both visible text and aria-invalid keeps sighted and assistive-tech users equally informed.
  3. 3Wiring the same handler to input events on both fields keeps the check live and symmetric as either field changes.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Live password-match validation in the DOM — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code