Conditional Required Fields
Make fields required based on another field value using discriminated unions or refine, so the schema encodes the dependency instead of the UI.
On this page
Introduction
This guide covers conditionally required fields driven by another value, a recurring concern in the form-validation scenario. A field that is sometimes required is a common source of bugs: the server accepts an incomplete payload because the UI forgot the rule, or the UI blocks a valid submit because it applied the rule too eagerly. Encoding the dependency in the schema removes both failure modes.
Pick the mechanism
Reach for a discriminated union when the tag changes the whole shape, and a refine when only one field flips, so the rule is expressed with the least ceremony.
The trade-off worth naming is that reach for a discriminated union when the tag changes the whole shape, and a refine when only one field flips, so the rule is expressed with the least ceremony adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Discriminated union shape
Branch on the tag so each variant has its own required set, and the parsed type narrows to the branch, which removes a runtime cast.
The trade-off worth naming is that branch on the tag so each variant has its own required set, and the parsed type narrows to the branch, which removes a runtime cast adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
const Contact = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('email'), email: z.string().email() }),
z.object({ kind: z.literal('phone'), phone: z.string().min(6) }),
]);
Refine for one field
When only a single field becomes required, a refine that checks the trigger and adds an issue to that field is shorter than a union and still lives in the schema.
The trade-off worth naming is that when only a single field becomes required, a refine that checks the trigger and adds an issue to that field is shorter than a union and still lives in the schema adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
const S = z.object({
hasCompany: z.boolean(),
company: z.string().optional(),
}).superRefine((v, ctx) => {
if (v.hasCompany && !v.company) ctx.addIssue({ code:'custom', message:'Company required', path:['company'] });
});
Share the schema
Use the same schema on client and server so the conditional rule cannot drift, which is the main reason to encode it in the schema rather than the component.
The trade-off worth naming is that use the same schema on client and server so the conditional rule cannot drift, which is the main reason to encode it in the schema rather than the component adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Drive the UI
Read the parsed schema to decide which fields to render as required, so the visual marker matches the enforced rule instead of a hardcoded assumption.
The trade-off worth naming is that read the parsed schema to decide which fields to render as required, so the visual marker matches the enforced rule instead of a hardcoded assumption adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Test both branches
Assert the trigger-met branch rejects a missing field and the trigger-absent branch accepts it, so the conditional cannot be inverted by a refactor.
The trade-off worth naming is that assert the trigger-met branch rejects a missing field and the trigger-absent branch accepts it, so the conditional cannot be inverted by a refactor adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Sources
Sources: Zod discriminatedUnion, JSON Schema if/then.
FAQ
- Discriminated union or refine for conditional fields?
- Use a discriminated union when the whole shape changes by tag, since it narrows the type; use refine when only one field flips required, since it is less ceremony.
- How do I avoid the field being required on the client but not the server?
- Share one schema; do not hand-write a second rule on the client, because the two drift and the server accepts what the client blocks.
Report a problem with this articleOpens a pre-filled issue on GitHub.