You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In Zod cross-field validation can be achieved via .refine on the object, e.g.:
z.object({FLAG_A: {schema: z.boolean(),defaults: {_: false}},FLAG_B_DEPENDS_ON_FLAG_A: {schema: z.boolean(),defaults: {_: false}}}).refine({FLAG_A,FLAG_B_DEPENDS_ON_FLAG_A}=>{if(FLAG_B_DEPENDS_ON_FLAG_A&&!FLAG_A){returnfalse}returntrue;},()=>({path: ['FLAG_A'],message: '`FLAG_A` field is required to be true if `FLAG_B_DEPENDS_ON_FLAG_A` is true',}));
How might this be achieved with znv?
The text was updated successfully, but these errors were encountered:
Hmm... personally for these sorts of cases I think the best answer is often to encode this as an enum or a discriminated union.
In this particular case, you're describing three possible states: nothing, A, A and B. With Zod and TypeScript, this is easy to express in a type-safe way using enums:
If there's more complex state attached to each flag, this could potentially be expressed as a discriminated union instead.
Incidentally, I think this is a good rule of thumb not just for configuration but also for structuring code internally -- a union type of literals can express these constraints more accurately than two booleans can, because you can't constrain the two booleans to exclude the fourth, invalid state (B and not A) without scattering imperative logic around to check it.
As a side note, twelve factor best practices suggest that env vars should be granular and orthogonal to each other, so there's another reason to avoid this sort of interdependency across vars.
That said, I get that the real world can be messy sometimes, so I'd be open to hear out alternate solutions to this if someone can present a solid case where enums/discriminated unions might not be the best solution, and can sketch an unobtrusive API design for expressing this sort of interdependency in a type-safe way.
Given the following schema, I wish for the validation of
FLAG_B_DEPENDS_ON_FLAG_A
to depend on the value ofFLAG_A
:In Zod cross-field validation can be achieved via
.refine
on the object, e.g.:How might this be achieved with znv?
The text was updated successfully, but these errors were encountered: