Skip to content
Discussion options

You must be logged in to vote

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

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by reistr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants