TanStackT
TanStack4mo ago
16 replies
sacred-emerald

Field level validation possible?

Field level validation possible?

I'm working on an webapp with many forms and many types of input.

If I have a input field <AgeInputField/>, I want to do the input validation inside this component, not on the form level.

All manuals I've found, assume the validation is on the form level: you have to add all validations in each form.

Is there no way to do this on the input field level? This is not a rare use case, right?

So I have a field like this

export function IdFormField() { const field = useFieldContext<string>(); // Add validation function here return <div className={styles.inputLine}> <TextField label="Id" value={field.state.value} onChange={(event) => field.handleChange(event.target.value)} /> </div>; }

Then, in my form:

<form.AppField name="id"> {(field) => <field.IdField/>} </form.AppField>

I see there are functions like field.pushValue() and field.setErrorMap(), but they're poorly documented and I can't find how to use them.

An alternative solution would be to pass form to the input field component.

I'm developing with TypeScript, and to pass form properly typed, I have to use AppFieldExtendedReactFormApi<>
with 14 (fourteen!) generic parameters. I tried to use broad types, but couldn't make the types correct.

In short:

Where can I find documentation about the fieldAPI?

So, the API as listed here: https://tanstack.com/form/v1/docs/reference/classes/fieldapi
but with explanations, examples etcetera.

And if that's not possible, how can I pass form well typed to a component?
Was this page helpful?