Handling zod and backend errors
Assume, there is a form-level validation for fields - this is zod. Another validation happens during submit - backend API can return submission errors, e.g. "username taken".
How can I store and handle those backend errors? I was thinking
useState
with backend errors which are returned in another form-level validator. However, having any errors in the form will block submission (canSubmit
is then false
and onSubmit
won't be triggered).
Am I missing any obvious solution? Beside clearing each field backend errors on change - I would prefer to handle it on form level instead of pushing listeners to each field.4 Replies
rare-sapphireOP•6mo ago
I was also thinking to somehow use form store to save those values, but I'm not sure how to do it either
frail-apricot•6mo ago
What framework are you using / backend?
frail-apricot•6mo ago
https://tanstack.com/form/latest/docs/framework/react/examples/field-errors-from-form-validators might work for validating the username async
React TanStack Form Field Errors From Form Validators Example | Tan...
An example showing how to implement Field Errors From Form Validators in React using TanStack Form.
rare-sapphireOP•6mo ago
Backend is simple rest api in php. However it does not provide validation/dry-run mode. Frontend is React SPA. So the only moment when I learn about backend errors is when I attempt submission. This is why
onSubmit[Async]
validator isn't really a good option.
So the way we handled it is a bit around - on submission iterate backend errors, use setFieldMeta
with new error map to pass errors to each field. The zod validator runs as onChange
which clears backend errors upon first validation. So it's not perfect, but at least it gets past the form not allowing for submission.
I just wish I could set non-blocking errors, or at least have an option to provide canSubmit
callback, which allows me to make that decision based on current form state/errors. I'd love to see bit more control over errors and clear information on what influences canSubmit
But question still stands - does anyone know any better option?