CodexBloom - Programming Q&A Platform

React Hook Form: Dynamic Field Validation scenarios on Submit with Nested Structures

👀 Views: 127 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-16
react react-hook-form yup validation javascript

I've been banging my head against this for hours. Does anyone know how to I'm working with an scenario with form validation in React Hook Form when dealing with dynamic fields that include nested structures... I'm using version 7.0.0 and trying to implement a form that allows users to add multiple addresses, where each address contains `street`, `city`, and `zip` fields. The question arises when I try to validate the form on submit; the validation seems to skip nested fields. I've set up my validation schema using `Yup`, and while the top-level fields validate correctly, any nested fields throw the behavior `ValidationError: street is a required field` even when they are filled out. Here's a simplified version of my form setup: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; import * as Yup from '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'), zip: Yup.string().required('Zip code is required'), })), }); function AddressForm() { const { control, handleSubmit, formState: { errors } } = useForm({ resolver: yupResolver(schema), }); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="addresses" control={control} render={({ field }) => ( <div> {field.value.map((address, index) => ( <div key={index}> <input {...register(`addresses.${index}.street`)} placeholder="Street" /> {errors.addresses?.[index]?.street && <p>{errors.addresses[index].street.message}</p>} <input {...register(`addresses.${index}.city`)} placeholder="City" /> {errors.addresses?.[index]?.city && <p>{errors.addresses[index].city.message}</p>} <input {...register(`addresses.${index}.zip`)} placeholder="Zip Code" /> {errors.addresses?.[index]?.zip && <p>{errors.addresses[index].zip.message}</p>} </div> ))} </div> )} /> <button type="submit">Submit</button> </form> ); } ``` I've tried adjusting how I register the inputs and even experimented with different validation schemas, but the nested fields still seem to not validate properly. Is there a specific way I should be handling dynamic arrays with nested validations in React Hook Form? Any help would be greatly appreciated! This is part of a larger application I'm building. Any help would be greatly appreciated! This issue appeared after updating to Javascript 3.10. I'd really appreciate any guidance on this. The project is a CLI tool built with Javascript. What's the correct way to implement this? Is there a simpler solution I'm overlooking?