T
TanStack2y ago
equal-aqua

How to manually set an error of the form

Hi guys, I'm look for a way to set error to the field from the backend. I don't see anything in API. Is it something with form.setFieldMeta? In react-hook-form you can do setError("email", {type: "server", message: "Foo"})
6 Replies
equal-aqua
equal-aquaOP2y ago
Anybody?
adverse-sapphire
adverse-sapphire2y ago
Hi, I'm not really an expert, but I think async validation needs to be done in the validators (relevant docs: https://tanstack.com/form/latest/docs/guides/validation#asynchronous-functional-validation). If you check out the CodeBox of the React Simple Example, you'll see an async validator that runs whenever the "First name" input field is changed, and returns an error if the value of the field is "error". (You can see this on the screenshot. You'll need to wait a second for the error to appear. https://codesandbox.io/p/devbox/tanstack-form-example-react-simple-ojqjtw
Form and Field Validation | TanStack Form Docs
At the core of TanStack Form's functionalities is the concept of validation. TanStack Form makes validation highly customizable: You can control when to perform the validation (on change, on input, on blur, on submit...) Validation rules can be defined at the field level or at the form level
No description
rival-black
rival-black2y ago
You're exactly right @fuko ! Thanks so much for helping with these issues
wise-white
wise-white5mo ago
I have a use case where I'm signing up a user with better-auth in my onSubmit form handler. With the new haveIBeenPawned plugin it returns a PASSWORD_COMPROMISED error. I thought it would make the most sense to set that as a field error on password, but cant find a way to do so. This is what I was trying.
if (error?.code === 'PASSWORD_COMPROMISED') {
const meta = form.getFieldMeta('password')
if (!meta) return

return form.setFieldMeta('password', {
...meta,
errors: ['Please choose a more secure password']
})
}
if (error?.code === 'PASSWORD_COMPROMISED') {
const meta = form.getFieldMeta('password')
if (!meta) return

return form.setFieldMeta('password', {
...meta,
errors: ['Please choose a more secure password']
})
}
continuing-cyan
continuing-cyan5mo ago
you'd probably be better off moving that logic into the onSubmitAsync validator and leaving onSubmit empty. Since onSubmit isn't called if the onSubmitAsync validator errored, you can assume that the signup was successful at that point
wise-white
wise-white5mo ago
thanks for the help I was able to get it working exactly how I wanted!

Did you find this page helpful?