Sub topic 10
Validating fields that depend on each other
Some rules involve more than one field. A confirm-password field must match the password. An end date must come after a start date. HTML has no attribute for these rules, so you write them with the Constraint Validation API.
This chapter assumes you know required, pattern, validity, and setCustomValidity() from earlier chapters, and that you can attach event listeners in JavaScript.
Why attributes cannot do this
Attributes such as min, max, and pattern look at one control's own value. They cannot read a sibling field. To compare two fields, you run a check in JavaScript and report the result through setCustomValidity(). A non-empty string marks the field invalid with that message. An empty string clears the error.
A password confirmation
Put the error on the field the user must fix. Here that is the confirm field.
<form id="signup" action="/signup" method="post">
<label for="password">Password</label>
<input id="password" name="password" type="password" required minlength="8">
<label for="confirm">Confirm password</label>
<input id="confirm" name="confirm" type="password" required>
<button type="submit">Sign up</button>
</form>const password = document.getElementById('password');
const confirm = document.getElementById('confirm');
function checkMatch() {
confirm.setCustomValidity(
confirm.value === password.value ? '' : 'Passwords do not match.'
);
}
password.addEventListener('input', checkMatch);
confirm.addEventListener('input', checkMatch);Both fields listen for input. If the user edits the password after filling the confirm field, the confirm field's validity must update too. Listening on only one field is the most common bug here.
Re-run the rule on every change
A custom message stays set until you clear it. The browser does not re-check it for you. If you set the message once and never clear it, the field stays invalid even after the values match. Always write the rule so it sets either a message or an empty string, as checkMatch does.
A date range
The same pattern works for dates. Date inputs return strings in YYYY-MM-DD form, so you can compare them as strings. Skip the check when either field is empty. Let required report the empty case.
const start = document.getElementById('start');
const end = document.getElementById('end');
function checkRange() {
const bad = start.value && end.value && end.value < start.value;
end.setCustomValidity(bad ? 'End date must be on or after the start date.' : '');
}
start.addEventListener('input', checkRange);
end.addEventListener('input', checkRange);You can also set end.min = start.value so the browser enforces the bound and the date picker greys out earlier days. Use setCustomValidity() when you want a specific message, or when the rule is more complex than a bound.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Listening on only the confirm field | Editing the password leaves a stale result | Listen on both fields |
| Never clearing the message | The field stays invalid forever | Always pass `''` when the rule passes |
| Setting the error on the wrong field | The user sees the message on a field that is fine | Attach it to the field they must change |
| Checking when a field is empty | Confusing duplicate messages | Let `required` handle empty values |
| Relying on this check for security | A client can skip it | Repeat the rule on the server |
Testing the rule
Run the check once on page load if the browser may restore values (for example after a back navigation). Then confirm in the console:
confirm.validity.customError; // true while the passwords differ
confirm.checkValidity(); // false while the passwords differExercise
A user fills in both password fields correctly, then goes back and changes the first password. The form now submits even though the passwords differ. What is missing from the code, and what is the fix?
Show answer
The match check runs only when the confirm field changes, so the old empty custom message stays in place. Add the same input listener to the password field so checkMatch runs after either field changes.