React Hook Form validation not working with custom components

clock icon

asked 4 days ago

message icon

0

eye icon

0

I'm building a form using React Hook Form with Zod validation, but I'm having trouble getting validation errors to display in my custom input components.

Current Setup

Here's my form setup with React Hook Form:

1
2const form = useForm<z.infer<typeof MySchema>>({
3
4 resolver: zodResolver(MySchema),
5
6 defaultValues: {
7
8 email: '',
9
10 password: '',
11
12 },
13
14});
15
1
2const form = useForm<z.infer<typeof MySchema>>({
3
4 resolver: zodResolver(MySchema),
5
6 defaultValues: {
7
8 email: '',
9
10 password: '',
11
12 },
13
14});
15

Custom Input Component

1
2const CustomInput = ({ label, name, ...props }) => {
3
4 const { control } = useFormContext();
5
6
7
8 return (
9
10 <FormField
11
12 control={control}
13
14 name={name}
15
16 render={({ field }) => (
17
18 <FormItem>
19
20 <FormLabel>{label}</FormLabel>
21
22 <FormControl>
23
24 <Input {...field} {...props} />
25
26 </FormControl>
27
28 <FormMessage />
29
30 </FormItem>
31
32 )}
33
34 />
35
36 );
37
38};
39
1
2const CustomInput = ({ label, name, ...props }) => {
3
4 const { control } = useFormContext();
5
6
7
8 return (
9
10 <FormField
11
12 control={control}
13
14 name={name}
15
16 render={({ field }) => (
17
18 <FormItem>
19
20 <FormLabel>{label}</FormLabel>
21
22 <FormControl>
23
24 <Input {...field} {...props} />
25
26 </FormControl>
27
28 <FormMessage />
29
30 </FormItem>
31
32 )}
33
34 />
35
36 );
37
38};
39

Zod Schema

1
2const MySchema = z.object({
3
4 email: z.string().email('Invalid email format'),
5
6 password: z.string().min(8, 'Password must be at least 8 characters'),
7
8});
9
1
2const MySchema = z.object({
3
4 email: z.string().email('Invalid email format'),
5
6 password: z.string().min(8, 'Password must be at least 8 characters'),
7
8});
9

The Problem

  1. Form submission is blocked correctly when validation fails

  2. form.formState.errors contains the error messages

  3. But <FormMessage /> doesn't display anything

  4. No error styling is applied to the inputs

What I've Tried

  • Used useFormContext() instead of passing control as prop

  • Tried <FormMessage /> vs <FormMessage>{error?.message}</FormMessage>

  • Checked that form provider wraps the component properly

  • Verified schema validation works independently

Expected Behavior

When validation fails, I expect to see error messages below each input field and error styling on the input borders.

Environment

  • React 18.2.0

  • React Hook Form 7.45.0

  • Zod 3.22.0

  • @hookform/resolvers 3.1.0

Has anyone encountered this issue with custom components and React Hook Form? Any help would be appreciated!

0 Answers

Filters

No answers found

It seems there are no answers yet. Be the first to answer a question.

Write your answer here

Top Questions