Is there any good way to make react-hook-form work with async validation + zod superRefine? #11942
Replies: 3 comments 1 reply
-
|
Hi @alex-collibra, Here's my way of doing it. Hope this would help!. Things to Note:
|
Beta Was this translation helpful? Give feedback.
-
|
This is exactly where forms get painful in modern React. Async validation against a backend is a very common use case, but putting it inside zod superRefine/resolver can quickly become hard to control. The problem is not only validation itself, but also:
In my experience, backend validation is often better treated as an explicit field-level/domain check, not hidden too deeply inside the schema resolver. Schema validation is great for synchronous structure/rules. |
Beta Was this translation helpful? Give feedback.
-
|
I would avoid putting this kind of backend check inside A schema resolver is a great place for local, deterministic validation. A backend uniqueness/eligibility check has a different lifecycle: debounce, cancellation, stale responses, loading state, and often “only validate this one field”. Hiding all of that inside the resolver is what usually causes the The pattern that has been the least painful for me is:
Sketch: const username = useWatch({ control, name: "username" })
useEffect(() => {
if (!username) return
const controller = new AbortController()
const timeout = window.setTimeout(async () => {
const result = await api.checkUsername(username, {
signal: controller.signal,
})
if (!result.available) {
setError("username", {
type: "remote",
message: "This username is already taken",
})
} else {
clearErrors("username")
}
}, 400)
return () => {
controller.abort()
window.clearTimeout(timeout)
}
}, [username, setError, clearErrors])If the remote validation must block submit, run the same backend check in |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a pretty valid usecase, in my opinion: we need to send a value to backend, then backend does some validation and returns an error code back.
I tried a lot of different things, without luck so far. As validation relies on BE response, I believe superRefine is the only way to do it.
However, I faced a lot of issues.
isValidflag isfalse.The closest behaviour I could get to so far is using this example #40 (comment)
However, it is still causing an issue with #4 when
isValidatingbecomes enabled, when it shouldn't.Has anyone every had any luck with making it work? It seems like a lot of pain for smth relatively common 😔
Beta Was this translation helpful? Give feedback.
All reactions