Strict check with default value #5487
-
|
Hello,
Is it possible with zod? |
Beta Was this translation helpful? Give feedback.
Answered by
BrendanC23
Dec 2, 2025
Replies: 1 comment
-
|
I don't think there's a straightforward way to conditionally have a default value. You will likely need two different schemas. You can either define two fully independent schemas or use a base schema. This is one solution: const schemaBase = z.object({
field: z.string().optional(), // Field will be optional and will not have a default
});
const schemaRequired = schemaBase.refine((data) => Boolean(data.field), {
error: "This field is required.",
path: ["field"]
});
// This could likely also be done with extend() if the base schema doesn't have too much nesting
const schemaWithDefault = schemaBase.transform((data) => {
if (!data.field) data.field = "default";
return data;
}); |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
reistr
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think there's a straightforward way to conditionally have a default value. You will likely need two different schemas. You can either define two fully independent schemas or use a base schema. This is one solution: