Sub topic 6
Conditional Fields and Dependent Logic
This chapter assumes you know basic HTML form elements, can read TypeScript, and understand how a browser submits form data. It also assumes you have seen the form state model from the earlier chapter: values, touched, dirty, and errors.
A conditional field is a field that appears, disappears, or changes its rules based on the answer to another field. Examples include a shipping address that only matters when the user picks "ship to me", or a company name that only matters for business accounts. Conditional logic keeps forms short. It also creates bugs that simple forms never have.
Why conditional fields cause bugs
A hidden field is still a field. Unless you decide otherwise, it keeps its value, it can still fail validation, and it can still be sent to the server. Most conditional-field bugs come from that gap between "not visible" and "not part of the form".
Common failures:
- A user picks "ship", types an address, switches to "pickup", and the old address is still submitted.
- A hidden required field blocks the "Next" button, and the user sees no error because the field is not on screen.
- A field is removed from the page, so a screen reader user is never told that the form changed.
- The user toggles an option back and forth and loses what they typed.
The rest of the chapter gives you a model that avoids each of these.
Model visibility as data
Do not scatter if statements across your markup. Declare, for each field, the condition under which it is visible. The rule then lives in one place and can be used by rendering, validation, and submission alike.
type Values = Record<string, string>;
type Field = {
name: string;
visibleWhen?: (values: Values) => boolean;
};
const fields: Field[] = [
{ name: "delivery" },
{ name: "address", visibleWhen: (v) => v.delivery === "ship" },
];
function activeValues(values: Values): Values {
const result: Values = {};
for (const field of fields) {
if (!field.visibleWhen || field.visibleWhen(values)) {
if (field.name in values) result[field.name] = values[field.name];
}
}
return result;
}activeValues returns only the values of fields that are visible right now. A field with no visibleWhen is always visible. If the user chose "ship" and typed an address, then switched to "pickup", activeValues drops the address.
Use activeValues in three places:
- Rendering. Show only fields whose condition is true.
- Validation. Validate only the fields in the active set.
- Submission. Send only the active values.
If all three use the same function, they cannot disagree.
Keep the value or clear it?
When a field becomes hidden, you must decide what happens to its stored value. There are two reasonable choices, and they trade off differently.
| Strategy | What it does | Good for | Risk |
|---|---|---|---|
| Keep, but filter on submit | The value stays in state. `activeValues` leaves it out of validation and the payload. | Toggles the user may flip back, such as delivery method | Stale data if you forget to filter somewhere |
| Clear on hide | The value is deleted when the field hides. | Sensitive data, or answers that no longer make sense after the change | User loses typing if they toggle by accident |
Keeping the value and filtering is usually the better default. It is forgiving, and the filter is a single function. Clear the value when keeping it would be wrong, for example when the options of a dependent field change and the old answer is no longer valid (see below).
Whichever you choose, never rely on the server ignoring extra fields. Filter before you send.
Dependent options
Sometimes the second field is always visible, but its choices depend on the first. A country selects the list of regions. A product type selects the list of sizes.
The failure here is a stale selection. The user picks country "Canada", region "Ontario", then changes the country to "France". "Ontario" is not a valid French region, but it is still in state.
Handle this when the parent value changes:
const regionsByCountry: Record<string, string[]> = {
CA: ["Ontario", "Quebec"],
FR: ["Bretagne", "Normandie"],
};
function setCountry(values: Values, country: string): Values {
const regions = regionsByCountry[country] ?? [];
const keepRegion = regions.includes(values.region ?? "");
return {
...values,
country,
region: keepRegion ? values.region : "",
};
}The region is kept only if it is still a valid choice. Otherwise it is reset to an empty string, and the field's required validation will ask the user to choose again.
Tell the user when you do this. A silent reset looks like a bug. A short message such as "Region cleared because you changed the country" in a live region (covered below) is enough.
Dependent rules, not only dependent visibility
A field can stay visible while its rules change. A phone number might be optional by default but required when the user ticks "Contact me by phone". A postal code format depends on the country.
Express these as functions of the current values, just like visibility:
type Rule = {
name: string;
requiredWhen?: (values: Values) => boolean;
};
const rules: Rule[] = [
{ name: "phone", requiredWhen: (v) => v.contactByPhone === "yes" },
];
function validateRequired(values: Values): Record<string, string> {
const errors: Record<string, string> = {};
for (const rule of rules) {
const required = rule.requiredWhen?.(values) ?? false;
if (required && !values[rule.name]?.trim()) {
errors[rule.name] = "Enter a phone number so we can call you.";
}
}
return errors;
}Combine this with visibility: a field that is hidden is never required. Run validateRequired on the result of activeValues, not on the raw values, so a hidden required field cannot block progress.
Revalidating when a dependency changes
If field B depends on field A, a change to A can make B's existing error wrong. For example, the user sees "Enter a phone number", then unticks "Contact me by phone". The phone error must disappear, even though the user never touched the phone field.
Two rules prevent stale errors:
- When a field changes, recompute errors for every field that depends on it, not only for the field that changed.
- Only show a recomputed error if the dependent field has been touched or the user has attempted to move forward. Otherwise ticking a box could cause a new error to appear on a field the user has not reached yet.
The second rule connects to validation timing. A field that just became required should not start in an error state. Show the error after blur or after a failed "Next", as you would for any field.
Conditions that span steps
In a multi-step flow, a condition on step 1 can change whether step 3 exists at all. For instance, "I have no dependants" removes the whole dependants step.
Treat the list of steps as computed from the values, not as a fixed array:
type Step = { id: string; visibleWhen?: (v: Values) => boolean };
const allSteps: Step[] = [
{ id: "account" },
{ id: "dependants", visibleWhen: (v) => v.hasDependants === "yes" },
{ id: "review" },
];
function activeSteps(values: Values): Step[] {
return allSteps.filter((s) => !s.visibleWhen || s.visibleWhen(values));
}Navigation then moves through activeSteps(values). Progress indicators must use the same list, so "Step 2 of 3" becomes "Step 2 of 2" when the step drops out. Warn the user if their change alters the number of steps, because a progress bar that shrinks without explanation is confusing.
If the user is on step 3 and goes back to change an answer that removes step 3's branch, the flow should resume at the next remaining step, not at a step that no longer exists.
Accessibility of changing forms
When a field appears because of the user's choice, a sighted user sees it. A screen reader user may not. Three practices help:
- Place new fields directly after the control that reveals them. The reading order then matches the cause.
- Use native controls for the trigger. Radio buttons, checkboxes, and selects already announce their state. A custom toggle needs the right role and state attributes.
- Announce changes that the user would not otherwise notice. Use a polite live region for messages such as "Shipping address fields added" or "Region cleared".
<fieldset>
<legend>Delivery method</legend>
<label><input type="radio" name="delivery" value="ship"> Ship to me</label>
<label><input type="radio" name="delivery" value="pickup"> Pick up in store</label>
</fieldset>
<div id="address-group">
<label for="address">Street address</label>
<input id="address" name="address" autocomplete="street-address">
</div>
<p id="form-status" role="status"></p>When the user selects "ship", show address-group and set the text of form-status to "Street address field added". Do not move keyboard focus to the new field. The user is still on the radio button and may want to keep browsing the options.
Avoid hiding fields with disabled as a substitute for removal. Disabled inputs are skipped by keyboard navigation and are not submitted, but they stay visible and confuse users who wonder why they cannot edit them. If a field is not relevant, remove it from the page, or hide it with the hidden attribute so it leaves the accessibility tree too. Hiding with only a visual trick such as zero opacity leaves it reachable by keyboard.
Common mistakes
- Validating the raw values. Always validate the active set.
- Duplicating conditions. If the render code and the submit code each hold their own copy of
delivery === "ship", they will drift apart. Define it once. - Deep chains of conditions. If A shows B, B shows C, and C shows D, users and testers struggle. Reduce the chain, or move the later fields to a separate step.
- Hiding required information behind a default. A default that quietly selects "pickup" can hide fields the user needed. Prefer an explicit choice for decisions with consequences.
- No test for toggling back and forth. Test the sequence: choose A, fill the revealed field, choose B, submit, and check the payload.
Testing conditional logic
Because visibility rules are pure functions, you can test them without a browser. A good set of cases for any conditional field is:
- The field is hidden by default, and absent from the payload.
- Selecting the trigger reveals the field, and it validates.
- Filling it, then un-selecting the trigger, removes it from the payload.
- Re-selecting the trigger restores the previous value, if you chose the "keep" strategy.
- A required field that is hidden does not block "Next".
Exercise
A user selects "Ship to me", types a street address, then switches to "Pick up in store" and submits. The server receives the street address. Which function from this chapter should have prevented this, and where should it be applied?
Show answer
activeValues should have been applied to the form values before submission, so only fields whose visibleWhen condition is true are sent. The same filtered set should also be used for validation and rendering so the three never disagree. The server should additionally ignore fields that do not apply to the chosen delivery method.
Exercise
A form has a required "Phone" field that appears only when "Contact me by phone" is ticked. The user ticks the box, sees the required error after pressing Next, then unticks the box. The error is still shown. What went wrong, and how do you fix it?
Show answer
The errors were not recomputed when the dependency changed. Fix it by recomputing errors for all fields that depend on the changed field whenever it changes, using the active values. Once the phone field is hidden, it is no longer in the active set, so it has no error and does not block Next.
Exercise
A country select controls a region select. The user chooses "CA" and "Ontario", then changes the country to "FR". What should happen to the region value, and what should the user be told?
Show answer
"Ontario" is not a valid French region, so the region should be reset to an empty value, and the required rule will then ask the user to pick again. The user should be told about the reset, for example through a polite live region message such as "Region cleared because you changed the country".