Course contentsShow
← Web Development
Lesson 915 of 2,98216. Forms and ValidationFree lesson

Validating Against Multiple Fields

Implement validation rules that compare values across multiple form fields, like password confirmation.

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:

  1. Listen for input events on both fields
  2. Compare their values
  3. 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.