CodexBloom - Programming Q&A Platform

React Hook Form: How to handle dynamic fields with validation on nested objects?

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

This might be a silly question, but I've spent hours debugging this and I'm relatively new to this, so bear with me... I'm currently working on a form using React Hook Form (v7.32.0) that requires handling dynamic fields for an array of nested objects. The form allows users to add multiple addresses, each containing a street, city, and postal code. I've set up the form and validation using `yup`, but I'm facing issues with dynamically adding and removing fields while ensuring the validation schema updates accordingly. Here’s a snippet of my form setup: ```javascript import React from 'react'; import { useForm, useFieldArray } from 'react-hook-form'; import * as yup from 'yup'; import { yupResolver } from '@hookform/resolvers/yup'; const schema = yup.object().shape({ addresses: yup.array().of(yup.object().shape({ street: yup.string().required('Street is required'), city: yup.string().required('City is required'), postalCode: yup.string().required('Postal Code is required').matches(/^[0-9]{5}$/, 'Must be exactly 5 digits'), })) }); function AddressForm() { const { register, control, handleSubmit, formState: { errors } } = useForm({ resolver: yupResolver(schema), defaultValues: { addresses: [{ street: '', city: '', postalCode: '' }] }, }); const { fields, append, remove } = useFieldArray({ control, name: 'addresses', }); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {fields.map((item, index) => ( <div key={item.id}> <input {...register(`addresses.${index}.street`)} placeholder="Street" /> <p>{errors.addresses?.[index]?.street?.message}</p> <input {...register(`addresses.${index}.city`)} placeholder="City" /> <p>{errors.addresses?.[index]?.city?.message}</p> <input {...register(`addresses.${index}.postalCode`)} placeholder="Postal Code" /> <p>{errors.addresses?.[index]?.postalCode?.message}</p> <button type="button" onClick={() => remove(index)}>Remove</button> </div> ))} <button type="button" onClick={() => append({ street: '', city: '', postalCode: '' })}>Add Address</button> <input type="submit" /> </form> ); } ``` When I add multiple addresses and remove one, the validation messages seem to persist for the fields that are no longer rendered. Additionally, I'm not sure if I'm managing the state correctly for validation, especially when using `yup`. I would appreciate any guidance on how to ensure that the validation state syncs correctly with the dynamic fields. Is there a best practice for handling this in React Hook Form? I'm working on a web app that needs to handle this. The stack includes Javascript and several other technologies. Any help would be greatly appreciated! Is there a better approach?