I am creating a app using T3 stack + react-hook-form + zodResolver:@hookform/resolvers/zod
I have a zod schema defined as below
export const AccountSchema = z.object({
id: z.string().uuid().optional(),
title: z.string().min(1, { message: 'Title is required' }),
description: z.string().min(1, { message: 'Description is required' }),
});
export type Account = z.infer<typeof AccountSchema>;
And in a component I am making use of useForm Hook as below
const editForm = useForm<Account>({ resolver: async (val, ctx, opt) => {
const res = await zodResolver(AccountSchema)(val, ctx, opt);
console.log('Validation Result: ', res, val);
return zodResolver(AccountSchema)(val, ctx, opt);
}});
form Submit Handler:
onSubmit={void editForm.handleSubmit(() => console.log('success'), (val) => console.log('Errors: ', val))}
Packages used:
"zod" -> "3.20.7"
"@hookform/resolvers" -> "2.9.11"
"react-hook-form" -> "7.43.5"
Issue:
Looking at the console log, I can see zodResolver is passing correct errors to useForm resolver but in the formState object errors is always undefined
ie: editForm.formState.errors.title is always returning as undefined.
Also on submit always reloads the page irrespective of the form being valid or invalid.
2
Answers
Wow. The "void" before handleSubmit was causing the issue. Had added void due to eslint@typescript-eslint/no-misused-promises rule.
Well, it just happened to me and turned out that I’m calling the wrong onSubmit action in the form field:
Then, changing the form onSubmit solved the issue:
Hope this helps out.