Search code examples
typescriptnext.jsreact-hook-formzod

React hook form with zod resolver optional field


I want to make a form with React-hook-form and zod resolver where all fields are optional but fields still required despite making them optional in zod schema:

const schema = z.object({
    name: z.string().min(3).max(50).optional(),
    description: z.string().min(3).max(255).optional(),
    image: clientImageSchema.optional(),
  })
const {...} = useForm({ resolver: zodResolver(schema) }) 

when submitting the form with blank inputs it validates fields as required. Where is the error or the mistake ?


Solution

  • I had the same issue. There may be some bug or issue regarding the handling of empty strings. There was similar thing happening with enums https://github.com/react-hook-form/react-hook-form/issues/3985.

    For now just running the field with .preprocess() seems to be working. What I mean is:

    const schema = z.object({
      // Watch out, z.preprocess takes two arguments
      foo: z.preprocess(
        (foo) => {
          // this line won't work
          // return foo
    
          // this line will work, dunno why
          // console.log(typeof email)
    
          // I'm using this
          if (!foo || typeof foo !== 'string') return undefined
          return foo === '' ? undefined : foo
        },
        z
          .string()
          .email({
            message: 'Please correct your email address',
          })
          .optional(),
      ),
    })
    

    So this will give us an optional field that will be validated as an email field once not-empty. There may be some other way but that's what I've found.