Validating Against Multiple Fields
What you'll learn: How to create validation rules that compare values across multiple form fields, such as ensuring a password and its confirmation match.
The Need for Cross-Field Validation
Sometimes a single field's validity depends on the value of another field. The classic example is password confirmation: the "confirm password" field is only valid if it matches the "password" field. Since HTML's built-in constraint validation works on individual fields, you need custom JavaScript to compare across fields.
How It Works
You'll typically use the setCustomValidity() method on the dependent field (like "confirm password") and trigger validation when either field changes. Here's the pattern:
- Listen for
inputevents on both fields - Compare their values
- Call
setCustomValidity()with an error message if they don't match, or an empty string if they do
const password = document.getElementById('password');
const confirmPassword = document.getElementById('confirmPassword');
function validatePasswords() {
if (password.value !== confirmPassword.value) {
confirmPassword.setCustomValidity('Passwords do not match');
} else {
confirmPassword.setCustomValidity('');
}
}
password.addEventListener('input', validatePasswords);
confirmPassword.addEventListener('input', validatePasswords);
Why Both Fields?
You attach listeners to both fields because if the user corrects the password field after already filling in confirmation, you want the error to clear immediately—not wait until they touch the confirmation field again.
Key Takeaway: Cross-field validation requires custom JavaScript to compare values and use setCustomValidity() on the dependent field, with event listeners on all relevant fields for responsive feedback.