Sub topic 10
Validating Fields That Depend on Each Other
Some rules cannot be checked by looking at one field alone. A confirmation password must equal the password. A check-out date must come after the check-in date. A phone number is required only if the user asked to be called. This chapter shows how to express those rules with the Constraint Validation API, and where the approach breaks down.
It assumes you know the built-in constraint attributes, how validity and validationMessage work, and how setCustomValidity marks a control invalid. It also assumes basic event handling in JavaScript.
Why built-in attributes fall short
Attributes such as required, min, and pattern are declared on one control and evaluated against that control's own value. The browser has no attribute for "this value must equal that one". Cross-field rules are therefore written in JavaScript and reported through the same channel as the built-in checks, so the browser still blocks submission, shows a message, and applies :user-invalid styling.
Common shapes of cross-field rules:
| Rule | Example | Best mechanism |
|---|---|---|
| Equality | Password and confirmation | `setCustomValidity` on the confirmation field |
| Ordering | End date after start date | Dynamic `min`, or `setCustomValidity` |
| Conditional requirement | Phone required if "call me" is checked | Toggle the `required` property |
| At least one of a group | One notification channel chosen | `setCustomValidity` on one control in the group |
The core pattern: recompute on every change
A custom error set with setCustomValidity stays until you clear it with an empty string. The browser never clears it for you, even if the user fixes the problem. That is the main source of bugs here: a field that looks correct but still blocks submission.
The reliable pattern has three parts:
- Put each rule in a function that returns an error message, or an empty string when the rule passes.
- Call
setCustomValiditywith that result every time, so a passing rule always clears the old error. - Run all rules whenever any field the rule depends on changes.
The third part matters most. If the user edits the password after typing a matching confirmation, the confirmation field's input event never fires. A rule that listens only on the confirmation field leaves a stale result. Listening on the form catches every field.
A complete example
The form below combines four rules: date ordering, password confirmation, a conditional phone requirement, and an at-least-one checkbox group.
<form id="booking" action="/booking" method="post">
<label for="start">Check-in</label>
<input id="start" name="start" type="date" required>
<label for="end">Check-out</label>
<input id="end" name="end" type="date" required>
<label for="password">Password</label>
<input id="password" name="password" type="password" required minlength="8"
autocomplete="new-password">
<label for="confirm">Confirm password</label>
<input id="confirm" name="confirm" type="password" required
autocomplete="new-password">
<label><input id="call-me" name="call_me" type="checkbox"> Call me to confirm</label>
<label for="phone">Phone</label>
<input id="phone" name="phone" type="tel" autocomplete="tel">
<fieldset>
<legend>Notify me by (choose at least one)</legend>
<label><input id="notify-email" name="notify" value="email" type="checkbox"> Email</label>
<label><input id="notify-sms" name="notify" value="sms" type="checkbox"> SMS</label>
</fieldset>
<button type="submit">Book</button>
</form>const form = document.getElementById('booking');
const byId = (id) => document.getElementById(id);
const rules = [
{
target: 'end',
message() {
const start = byId('start').value;
const end = byId('end').value;
// Skip when either is empty: "required" already reports that.
// ISO yyyy-mm-dd strings compare correctly as text.
return start && end && end <= start
? 'Check-out must be after check-in.'
: '';
},
},
{
target: 'confirm',
message() {
return byId('confirm').value !== byId('password').value
? 'Passwords do not match.'
: '';
},
},
{
target: 'notify-email',
message() {
const checked = form.querySelectorAll('input[name="notify"]:checked');
return checked.length === 0
? 'Choose at least one way to be notified.'
: '';
},
},
];
function validateAll() {
// Conditional requirement: use the built-in valueMissing check.
byId('phone').required = byId('call-me').checked;
for (const rule of rules) {
byId(rule.target).setCustomValidity(rule.message());
}
}
form.addEventListener('input', validateAll);
form.addEventListener('change', validateAll);
form.addEventListener('reset', () => setTimeout(validateAll, 0));
validateAll();Points to notice in this code:
validateAllcallssetCustomValidityfor every rule on every run. A rule that now passes passes'', which clears the old error.- The
resethandler usessetTimeoutbecause theresetevent fires before the values are restored. Reading values immediately would see the old data. - The initial call to
validateAll()covers the page-load state, including values the browser restores or autofills. - The phone rule needs no custom message. Setting
requiredmakes the browser reportvalueMissingwith its own localized text.
Choosing which field carries the error
setCustomValidity applies to one control, and the browser shows the message at that control. Put the error on the field the user should change:
- For equality, use the confirmation field, since the first field was presumably typed carefully.
- For date ordering, use the later date.
- For a group, use the first control in the group. Radio buttons sharing a
namehave a built-in group rule: putrequiredon any one of them. Checkboxes have no such rule, so a custom check is the only option.
For date ranges you can often avoid custom messages. Setting end.min = start.value whenever the start changes makes the browser raise rangeUnderflow with a message that names the minimum date. Note that min is inclusive, so a same-day booking passes. Use the custom approach, as in the example, when the end must be strictly later.
Common errors
- Stale errors. Setting a message only in the failing branch and forgetting the clear. The field stays invalid after the user corrects it.
- Listening on one field. Editing the password does not fire an event on the confirmation field. Listen on the form or on every field a rule reads.
- Script-driven changes. Setting
field.value = ...in code fires noinputevent. CallvalidateAll()yourself afterward. - Rules that duplicate built-in checks. If a custom rule reports "required" for an empty value, it overrides the built-in message. Return
''for empty values and letrequiredhandle them. - Disabled controls. A disabled control has
willValidateset to false and is skipped on submission. A custom error on a field that becomes disabled stops blocking the form, which may or may not be what you want. - Silent state.
setCustomValidityfires no event and shows nothing by itself. The message appears when the browser reports validity on submit, when you callreportValidity(), or when your own code readsvalidationMessage.
You can detect your own errors with field.validity.customError, which is true only when a non-empty custom message is set. This helps when your error display must tell a custom failure from a built-in one.
Accessibility of group and cross-field errors
The browser bubble is announced for the field it focuses, but a message tied to the first checkbox of a group reads oddly. If you render inline errors, put the message element next to the fieldset, link it with aria-describedby on the fieldset, and set aria-invalid on the controls involved. For the confirmation field, link the error text to that field directly. Keep the message specific: "Passwords do not match" says more than "Invalid value".
Repeat the rules on the server
Every rule above can be bypassed by a client that skips the page's JavaScript. The server must check the relationships too, and it should also treat unexpected types as errors.
function validateBooking(input) {
const errors = {};
const isDate = (v) =>
typeof v === 'string' &&
/^\d{4}-\d{2}-\d{2}$/.test(v) &&
!Number.isNaN(Date.parse(v));
if (!isDate(input.start)) errors.start = 'Enter a valid check-in date.';
if (!isDate(input.end)) errors.end = 'Enter a valid check-out date.';
if (!errors.start && !errors.end && input.end <= input.start) {
errors.end = 'Check-out must be after check-in.';
}
if (typeof input.password !== 'string' || input.password.length < 8) {
errors.password = 'Use at least 8 characters.';
} else if (input.confirm !== input.password) {
errors.confirm = 'Passwords do not match.';
}
if (input.call_me && !String(input.phone ?? '').trim()) {
errors.phone = 'Enter a phone number so we can call you.';
}
const notify = [].concat(input.notify ?? []);
if (notify.length === 0) errors.notify = 'Choose at least one way to be notified.';
return errors;
}Two details: the ordering check runs only when both dates parsed, so one bad value does not produce a second, confusing error, and notify is normalized with concat because a form with one checked box submits a string while several submit an array in many frameworks.
Exercise
A user types a password, types a matching confirmation, then goes back and changes the password. The confirmation field still shows no error and the form submits. Your code listens for input only on the confirmation field. What is wrong, and how do you fix it?
Show answer
The rule is not re-run when the password changes, because no event fires on the confirmation field. Its custom validity was cleared earlier and is now stale. Fix it by running the rule on every field it depends on, for example with one input listener on the form that calls a function that sets the confirmation field's custom message (or '' when the values match). Also repeat the equality check on the server.
Exercise
You write if (end <= start) end.setCustomValidity('Check-out must be after check-in.'); inside an input handler. After the user fixes the dates, the form still refuses to submit. Why, and what is the smallest change that fixes it?
Show answer
The custom message is never cleared. setCustomValidity leaves the error in place until it is called with an empty string. Compute the message first, then always call end.setCustomValidity(message), where message is '' when the dates are valid.
Exercise
A signup form must require a phone number only when a "Call me" checkbox is checked. Should you use a custom message or the required property, and what do you gain?
Show answer
Toggle phone.required = callMe.checked whenever the checkbox changes. The browser then reports valueMissing with its own localized message, the field matches the :required selector, and you avoid managing a custom error that you would have to clear.