I am using Shadcn Form which uses React-Hook-Form and Zod Resolver, The problem is when i submit the form by clicking the button while making the input incorrect for testing (Putting 1 char on 2 char validation), I am getting a Runtime ZodError
, showing the Zod schema validation error like this, Instead of populating the component. I don't know is it some version issues or something. zod^4.0.17
, react-hook-form^7.54.1
, @hookform/resolvers^3.9.1
{
"origin": "string",
"code": "too_small",
"minimum": 2,
"inclusive": true,
"path": [
"username"
],
"message": "Username must be at least 2 characters."
}
Example code,
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
const formSchema = z.object({
username: z.string().min(2, {
message: 'Username must be at least 2 characters.',
}),
});
function TestPage() {
// 1. Define your form.
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
username: '',
},
});
// 2. Define a submit handler.
function onSubmit(values: z.infer<typeof formSchema>) {
// Do something with the form values.
// ✅ This will be type-safe and validated.
console.log(values);
}
return (
<Form {...form}>
<form className="space-y-8" onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="shadcn" {...field} />
</FormControl>
<FormDescription>
This is your public display name.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Submit</Button>
</form>
</Form>
);
}
export default TestPage;
I found the issue, It is happening because version mismatch, I am using zod^4.0.17
and @hookform/resolvers^3.9.1
. When i update the @hookform/resolvers^5.2.1
(latest) Its working fine.