CodexBloom - Programming Q&A Platform

Next.js Form Handling with Zod Validation: how to to Handle Nested Object Errors Gracefully

πŸ‘€ Views: 19 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-02
next.js react-hook-form zod form-validation typescript JavaScript

I've spent hours debugging this and I'm stuck on something that should probably be simple... I'm working on a Next.js application and using Zod for form validation with react-hook-form. I have a nested object structure in my form, and when the validation fails, I get a generic behavior instead of specific messages related to each field. For example, I have a form that looks like this: ```javascript import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; const schema = z.object({ user: z.object({ name: z.string().min(2, { message: 'Name is too short' }), email: z.string().email({ message: 'Invalid email' }), }), age: z.number().min(18, { message: 'Must be at least 18' }), }); const MyForm = () => { const { register, handleSubmit, formState: { errors } } = useForm({ resolver: zodResolver(schema) }); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('user.name')} /> {errors.user?.name && <p>{errors.user.name.message}</p>} <input {...register('user.email')} /> {errors.user?.email && <p>{errors.user.email.message}</p>} <input type='number' {...register('age')} /> {errors.age && <p>{errors.age.message}</p>} <button type='submit'>Submit</button> </form> ); }; ``` I've tried accessing the nested errors using `errors.user?.name` and similar patterns, but when I submit the form with validation errors, the console shows that the `errors` object structure is not what I expect. Instead, I'm just getting an object with a single property named `user` that contains the validation errors, but it’s not being linked properly to the input fields in my form. I'm also using react-hook-form version 7.0.0 and Zod version 3.11.6. Should I be handling the nested validations differently? Any insights into how I can make sure that my behavior messages correspond correctly to their respective input fields would be greatly appreciated! I'm seeing a lot of `TypeError: want to read properties of undefined` when I try to access nested properties that should exist based on the validation results. How can I avoid this? I'm working on a web app that needs to handle this. Any ideas how to fix this? The project is a web app built with Javascript. Thanks, I really appreciate it!