T
TanStack15mo ago
sunny-green

ValidationError - Zod

I'm wondering why ValidationError doesn't return an array of strings, where each item is an error? According to this screenshot I'm expecting an array like [ "Password, must contain at least 8 characters" , "Password, must include tuna" ] It looks always return 1 item with the errors concat with , . The thing is, I want to display 1 error at the time, not all of them for a better UX. If I do it in a hacky way extracting the items based on , it won't work for error messages where I add a comma. Is there any workaround for this?
No description
No description
9 Replies
correct-apricot
correct-apricot15mo ago
Looks like it could be a problem with the Zod adapter maybe? Because ValidationError isn't meant to be an array
No description
sunny-green
sunny-greenOP15mo ago
What should be then? For example for pasaword field, if there are 3 errors, I'd like to show one at the time
correct-apricot
correct-apricot15mo ago
I don't know, because you haven't provided much info about your setup
sunny-green
sunny-greenOP15mo ago
I'll paste the whole code from the form to see what i'm doing wrong, thanks mate
correct-apricot
correct-apricot15mo ago
Looks like the zod adapter is the one that is smooshing them together
genetic-orange
genetic-orange15mo ago
If you want more controls on the errors you can pass a transformErrors function to the adapter. With zod might look like this to only get the first:
validatorAdapter: zodValidator({
transformErrors: (errors) => errors.map((error) => error.message)[0]
}),
validatorAdapter: zodValidator({
transformErrors: (errors) => errors.map((error) => error.message)[0]
}),
sunny-green
sunny-greenOP15mo ago
is joining all the zod errors in 1 single error applying for all the validators adapters? It looks like an opinionated decision for me. I'll have a look at the codebase and see how the adapters really work Thanks, I'll have a look at tranaformErrors
genetic-orange
genetic-orange15mo ago
Yes it's the default behavior
literary-plum
literary-plum14mo ago
I made a PR with a failing test (expecting the errors-array to have multiple items) a month ago – https://github.com/TanStack/form/pull/943 I looked through the code and it looks like multiple places would have to be touched - but only having one item in the errors-array feels wrong.
GitHub
test: verify zod validator returns ValidationError[] by Pascalmh · ...
For now this is just a failing test ToDo: implement the fix optional?: refactor the test - add a new test instead of extending the existing one refs #942

Did you find this page helpful?