CodexBloom - Programming Q&A Platform

React Hook Form Validation guide with Nested Objects in useForm

šŸ‘€ Views: 981 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-16
react react-hook-form validation JavaScript

I'm refactoring my project and I'm working with a question with validation in React Hook Form when dealing with nested objects. I have a form where I'm using `useForm` from React Hook Form v7. I expected that when I trigger validation on my nested fields, the validation errors would show up as expected. However, I'm only getting validation errors for the top-level fields and not for the nested ones. Here's a simplified version of my form setup: ```javascript import { useForm, Controller } from 'react-hook-form'; function MyForm() { const { control, handleSubmit, formState: { errors } } = useForm(); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="user.name" control={control} rules={{ required: true }} render={({ field }) => <input {...field} />} /> {errors.user?.name && <p>Name is required</p>} <Controller name="user.email" control={control} rules={{ required: true }} render={({ field }) => <input {...field} type="email" />} /> {errors.user?.email && <p>Email is required</p>} <button type="submit">Submit</button> </form> ); } ``` The above code works for top-level fields, but my validation for nested fields like `user.name` and `user.email` does not trigger. I know I’m supposed to use dot notation for nested fields, but the validation behavior messages aren't displaying even when I leave the inputs empty. I've also double-checked that my `rules` are correctly applied. I tried using `setError` to manually set the errors, but that feels like a workaround. Is there something I’m missing in my implementation? Any help would be greatly appreciated! Is this even possible?