CodexBloom - Programming Q&A Platform

React Hook Form: Validation not triggering on nested fields with useFormContext

πŸ‘€ Views: 49 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
react react-hook-form validation JavaScript

I'm trying to debug I've spent hours debugging this and I'm working on a project and hit a roadblock... I'm working with React Hook Form v7 and trying to implement validation for a nested object structure. My form has a nested structure for addresses, and I'm using `useFormContext` to manage the state across nested components. However, validation isn't triggering as expected when I submit the form. Instead of showing my custom error messages, the submission proceeds without any indication of validation issues. Here’s how I set up my form: ```javascript import { useForm, FormProvider } from 'react-hook-form'; import AddressForm from './AddressForm'; const MainForm = () => { const methods = useForm({ defaultValues: { name: '', address: { street: '', city: '', zip: '', }, }, mode: 'onBlur', }); const onSubmit = (data) => { console.log(data); }; return ( <FormProvider {...methods}> <form onSubmit={methods.handleSubmit(onSubmit)}> <input {...methods.register('name', { required: true })} placeholder="Name" /> <AddressForm /> <button type="submit">Submit</button> </form> </FormProvider> ); }; ``` And here’s how the nested `AddressForm` looks: ```javascript import { useFormContext } from 'react-hook-form'; const AddressForm = () => { const { register, formState: { errors } } = useFormContext(); return ( <div> <input {...register('address.street', { required: true })} placeholder="Street" /> {errors.address?.street && <span>This field is required</span>} <input {...register('address.city', { required: true })} placeholder="City" /> {errors.address?.city && <span>This field is required</span>} <input {...register('address.zip', { required: true, pattern: { value: /^[0-9]{5}$/, message: 'Invalid ZIP code' } } )} placeholder="ZIP" /> {errors.address?.zip && <span>{errors.address.zip.message}</span>} </div> ); }; ``` Despite setting up the validation, when I try to submit without filling the address fields, the form submits successfully without showing the respective error messages. I've double-checked the field names and ensured that they match the structure in my main form. Any insights on why validation might not be triggering for nested fields? I've also tried switching the `mode` to `onChange`, but it didn't help. Any suggestions would be appreciated! This is part of a larger CLI tool I'm building. Any ideas what could be causing this? Thanks in advance! Thanks for taking the time to read this!