T
TanStack•4mo ago
genetic-orange

How to trigger validation on submit (to show errors)?

I run my validators (zod schema) via onChange and show my errors only if the field is blurred like this:
export function getFieldError(field: AnyFieldApi) {
if (!field.state.meta.isBlurred) {
return
}

return field.state.meta.errors[0]?.message
}
export function getFieldError(field: AnyFieldApi) {
if (!field.state.meta.isBlurred) {
return
}

return field.state.meta.errors[0]?.message
}
This works fine and also revalidates if I change the field with an error, but it doesn't validate if the fields weren't touched yet and I hit the submit button. How can I trigger this or which fields do I need to check within the getFieldError function? When I click the submit button it should automatically trigger validation on every field and show the error message there. So what I want is basically: - show error message on blurred fields - hide error when typing inside error fields and value is valid - don't validate fields while typing that weren't touched - validate every field if form is submitted, regardless touched or not
3 Replies
flat-fuchsia
flat-fuchsia•4mo ago
check for submissionAttempts > 0
eastern-cyan
eastern-cyan•4mo ago
And add the onSubmit validator Fields are marked as touched when attemting to submit the form: https://github.com/TanStack/form/blob/2a82baa488fc4bddf985ee94e9bc219c70dd9ce5/packages/form-core/src/FormApi.ts#L1758-L1759
genetic-orange
genetic-orangeOP•4mo ago
ohh just checked with submissionAttempts + onSubmit and it works now 🥳 thanks guys @Luca | LeCarbonator @ksgn, appreciate the fast help 🫡

Did you find this page helpful?