T
TanStack2mo ago
ratty-blush

Best practice for sharing validation logic across reusable components in TanStack Form

Hi all, I'm investigating adopting TanStack Form for form composition within our React application. I've successfully composed a field component using TanStack Form, but I'm struggling to understand the best approach for including validation logic with reusable components. For example, I have a complex use case involving a coordinate input form (it allows text input, as well as selection via clicking on a map). Currently, the validation logic is built directly into the React component itself. Each time a user changes the value, it validates whether the coordinate is valid. I want to move towards the TanStack Form composition approach, but I'm confused about how to share this validation logic effectively. It feels like keeping the validation inside the coordinate input component goes against the recommended form-driven validation approach, where validators live outside components and are registered via the form configuration. However, if I remove the validation from the component, then every time someone uses this coordinate input elsewhere, they would have to remember to add the specific validator themselves. My questions are: What is the recommended pattern for sharing complex validation logic across multiple forms when using reusable input components in TanStack Form? Should the coordinate validation remain embedded within the component, or is there a way to tie it to the component by default while still following TanStack Form's validator registration model? How do others manage validators that are intrinsic to the concept of a field (e.g. a coordinate input that must always validate as a coordinate) without duplicating validator setup across forms? Any guidance or examples would be greatly appreciated to help structure our implementation cleanly. Thanks in advance!
2 Replies
exotic-emerald
exotic-emerald2mo ago
now that you've brought it up, field-level validation is more difficult to extract from the JSX section. TSF generally suggests form level validation over field level validation if you can, but if you have an idea for extracting it out of the JSX section and into the logic section, let us know!
ratty-blush
ratty-blushOP2mo ago
Currently I have it working now nicely with validators set outside of the CoordinteField component. Conceptually I was hoping for a pattern to be able to inject errors in to a parent form context. It looks like there is a function to set the error map, but I am struggling to understand the types and what would need to be passed in to it? https://tanstack.com/form/latest/docs/reference/classes/fieldapi#seterrormap
FieldApi | TanStack Form Docs
<!-DO NOT EDIT: this page is autogenerated from the type comments - Class: FieldApi<TParentData, TName, TData, TOnMount, TOnChange, TOnChangeAsync, TOnBlur, TOnBlurAsync, TOnSubmit, TOnSubmitAsync, T...

Did you find this page helpful?