Skip to content

Why do conditionally optional inputs do not show error message until all mandatory values are error free? #363

Discussion options

You must be logged in to vote

It's because zod will run .refine() or .transform() only if the schema is fulfilled. When you don't have a title provided, what zod see is an empty object (since Conform strip empty string) which doesn't satisfy the type as it expects title to be a string. So it stop running the transform.

To fix this, a common solution is to narrow down the scope of your schema:

const schema = z
  .object({
    title: z.string({
      required_error: "Title is required",
      invalid_type_error: "Title must be a string",
    }),
  }).and(
    // This schema not does not have title included
    z.object({
      category: z.string().optional(),
      custom_category: z.string().optional(),
    })
    .tra…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by waldothedeveloper
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