T
TanStack5w ago
stormy-gold

How is field.handleChange() work for nested fields? How is validation on nested fields handled?

I'm currently using Zod schema with nesting:
parent: z.object({
childA: ChildASchema
childB: ChildBSchema
})
parent: z.object({
childA: ChildASchema
childB: ChildBSchema
})
And in my form I'm using <form.Field name='parent.childA' ... />. 1. Do I have to be concerned about handling the parent's state? Or does using handleChange for both children properly update its state? 2. My second question question is do the childA and childB fields get checked against their respective schemas? And if so, are the errors still accessible via field.state.meta.errors?
3 Replies
passive-yellow
passive-yellow5w ago
To answer question 1: * calling "parent.childA"'s field.handleChange should update the parent value as expected * calling "parent"'s field.handleChange should update the children's value as expected. * meta state may not work as expected, such as isTouched. Those are specific to the field you called the change on. As for question 2: Yes, if you have a form validator schema, it will pass the whole object to validate against the zod schema. Caveat Paths in zod are as specific as possible by default. This means that you have the following things to look out for:
// works as expected, 'parent.childA' receives error
childA: z.number().int().min(5)

// zod maps this not to 'parent.childA', but to 'parent.ChildA.nested'.
// 'parent.childA' will not receive the error since it's not assigned to it.
// If you're using compound fields, you need to change the zod issue path.
childA: z.object({
nested: z.number().int().min(5)
})
// works as expected, 'parent.childA' receives error
childA: z.number().int().min(5)

// zod maps this not to 'parent.childA', but to 'parent.ChildA.nested'.
// 'parent.childA' will not receive the error since it's not assigned to it.
// If you're using compound fields, you need to change the zod issue path.
childA: z.object({
nested: z.number().int().min(5)
})
Of course this is not particularly helpful, so we're going to add a way to turn off field mapping as well as allowing compound field errors
stormy-gold
stormy-goldOP5w ago
Thank you! Also your response time is fast I need to commend your punctuality, it's genuinely insane
passive-yellow
passive-yellow5w ago
well, I just arrived at my workplace too early, might as well help out here

Did you find this page helpful?