T
TanStack2mo ago
correct-apricot

Typings on validation errors for fieldComponents

I'm trying to implement Zod in my Tanstack form, but I'm struggling to find a type safe way of presenting the errors from validation. My components are FieldComponents, and I want them to have their own error presentation but the type for field.form.state.errors is an any[] (pic 1). I'm a bit confused of what I need to do differently. If I try to access it from its executive parent then the type is undefined[] (pic 2). Any help would be greatly appreciated, and I can provide any further info that is needed. The full path works (pic 3), but I'd like to have it be properly typed.
No description
No description
No description
4 Replies
helpful-purple
helpful-purple2mo ago
To address your questions: * Validation errors can be of any shape. You want to use zod, which will be of the shape StandardSchemaV1Issue. Long word, but essentially means you will have a message property that is a string. * in Form Composition, your reuseable field can be used by any form, and therefore any validator. You cannot know the shape of the error beforehand. * Inside withForm, you have validators defined in formOptions which will tell it what errors could be. However, you don't have any validators specified in your form options (at least according to the error). It collapsed to undefined[]. for form composition, you have two options now: * Pass the errors as prop, which will have typing when calling the component. * Narrow unknown to an error message based on what you use, which is commonly either a error: string or error: { message: string }. Let me know if you need help with that one.
correct-apricot
correct-apricotOP2mo ago
Right, that makes sense, thank you. I've now included validators into my formOptions instead of only declaring them with the form, and am passing the validation message down to the fieldcomponent as a prop as shown in the picture. Would this be your recommendation?
No description
helpful-purple
helpful-purple2mo ago
that's one way, yes. I assume you're using zod on the form level? If so, keep in mind that zod validates all errors at once. It includes fields that haven't been touched yet. If you want to avoid bad UX, errors should not be visually shown if the field is not touched
correct-apricot
correct-apricotOP2mo ago
Yes, Zod on the form level. I'll make sure to check for touched fields as well. Greatly appreciate the help!

Did you find this page helpful?