T
TanStack12mo ago
inland-turquoise

Form Field Errors From Form Validators using Zod validate all fields

const form = useForm({
defaultValues: {
username: '',
age: 0,
},
validatorAdapter: zodValidator(),
validators: {
onChange: z.object({
username: z.string().min(3, 'Needs to be 3 chars long'),
age: z.number().min(13, 'You need to be 13'),
}),
},
});
const form = useForm({
defaultValues: {
username: '',
age: 0,
},
validatorAdapter: zodValidator(),
validators: {
onChange: z.object({
username: z.string().min(3, 'Needs to be 3 chars long'),
age: z.number().min(13, 'You need to be 13'),
}),
},
});
Using this the age field will have an error as soon as an onChange-Event has been fired from the username field the age field (in fact all fields) are validated and have an error. Reproduction: - Go to: https://stackblitz.com/edit/tanstack-form-a6vgcj?file=src%2Findex.tsx - Type something into the username input
2 Replies
other-emerald
other-emerald12mo ago
That's the intended behavior. You can use isTouched || isSubmitted to only show touched fields if youd like
inland-turquoise
inland-turquoiseOP12mo ago
Ah sure as I'm on the "Form" level here again the "Form" changed - not only the "Field" - makes sense. Ended up with this: state.meta.isTouched || form.state.isSubmitted (state is from the FieldApi)
<Field
name=
children={({ name, state, handleBlur, handleChange, form }) => (
// …
errorMessage={state.meta.isTouched || form.state.isSubmitted ? state.meta.errors?.[0] : null}
// …
)}
/>
<Field
name=
children={({ name, state, handleBlur, handleChange, form }) => (
// …
errorMessage={state.meta.isTouched || form.state.isSubmitted ? state.meta.errors?.[0] : null}
// …
)}
/>

Did you find this page helpful?