【问题标题】:React hook form with zod resolver optional fieldReact hook form with zod resolver optional field
【发布时间】:2022-12-28 01:45:08
【问题描述】:
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 ?
【问题讨论】:
标签:
typescript
next.js
react-hook-form
zod
【解决方案1】:
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)
// this line will also work
// 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.