CodexBloom - Programming Q&A Platform

React Hook Form: Custom Validation for Nested Fields Not Triggering on Submit

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

I'm stuck on something that should probably be simple. I'm working with React Hook Form v7 and trying to implement custom validation for nested fields within my form. The form structure is quite complex, with a dynamic array of objects and each object containing several fields. I have set up the validation rules using the `useForm` hook, but I'm encountering issues where the custom validation is not being triggered on form submission, causing the form to submit even when there are errors. Here’s a simplified version of my form setup: ```javascript import React from 'react'; import { useForm, useFieldArray } from 'react-hook-form'; const MyForm = () => { const { register, control, handleSubmit, formState: { errors } } = useForm(); const { fields, append, remove } = useFieldArray({ control, name: 'users', }); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {fields.map((item, index) => ( <div key={item.id}> <input {...register(`users.${index}.name`, { required: 'Name is required' })} /> {errors.users?.[index]?.name && <span>{errors.users[index].name.message}</span>} <input {...register(`users.${index}.age`, { required: 'Age is required', validate: value => value > 0 || 'Age must be greater than 0', })} /> {errors.users?.[index]?.age && <span>{errors.users[index].age.message}</span>} <button type="button" onClick={() => remove(index)}>Remove</button> </div> ))} <button type="button" onClick={() => append({})}>Add User</button> <input type="submit" /> </form> ); }; export default MyForm; ``` When I submit the form with invalid values (for instance, leaving the age empty), the form still submits successfully without showing any validation errors. I’ve tried checking the `formState.isValid` property and it returns true even when it shouldn't. Additionally, I've ensured that I am not directly manipulating the form values before submission. I suspect it might be an issue with how I’m handling nested validations or perhaps the way I'm registering the inputs. Has anyone else faced similar issues with nested fields and custom validations in React Hook Form? What could be the cause, and how can I ensure that the custom validations trigger correctly on submit? I'm working on a web app that needs to handle this. This is happening in both development and production on macOS. I'd be grateful for any help.