issue: isValid triggers validation function when "onChange" despite "onSubmit" modes #10215
Closed
1 task done
Labels
question
Further information is requested
Version Number
7.43.8
Codesandbox/Expo snack
https://codesandbox.io/s/react-hook-form-basic-forked-5gi2ng
Steps to reproduce
https://codesandbox.io/s/react-hook-form-basic-forked-5gi2ng , open the console. Due to the fact that
mode
andreValidateMode
are both"onSubmit"
, when you type something in the First Name field, nothing shows in the console. It's only when you click "Submit" button that "validateFn is executed" shows up. Everything is good.But when you change
formState: { errors }
toformState: { errors, isValid }
, you would think it's no big deal, but it actually has a huge impact on the (re)validation modes - as soon as you type something in the First Name field, "validateFn is executed" shows in the console. It behaves as if the modes are "onChange" (isValid
changes every time, theerrors
does not change every time, however).Expected behaviour
If the
validateFn
is an expensive async function, especially an API fetch function, you won't want to perform that when "onChange", you want to perform that when "onSubmit". And this issue causes a lot of trouble.It took me 2 or 3 hours to find out what had happened, I thought it was a problem of zod, or zodResolver, or Controller etc which I guessed could be incompatible with async validation function, but they are actually all good.
formState is wrapped with a Proxy, I guess something is done with it that causes this, I didn't read the source code though...
Solution for user: just don't use
isValid
(errors
or evenisDirty
is perfectly OK to use, it's justisValid
that has the issue).If you want to know if there's any error, just test if
formState.errors
is an empty object (const isEmptyObject = (obj: any) => typeof obj === 'object' && Object.keys(obj).length === 0;
)Suggestion for the library: Not sure if it's intended and whether
isValid
's behaviors should be changed, or maybe we can add a third mode -isValidMode
for it. But for now at leastformState.isValid
in the documentation should add a warning or something.The issue does not exist in older versions.
Starting from v7.7.2-beta.0, with
isValid
it validates the form at the first render, but not on every change.Starting from v7.39.0, with
isValid
it validates the form at the first render, and on every change.According to a v7.39.0 change of a test case "should update isValid even with mode set to onSubmit", it looks like it's intended? OK, but if so, we need a third mode
isValidMode
to control it.In v8.0.0-alpha.4, with
isValid
it validates the form at the first render, but not on every change (just like v7.7.2-beta.0)What browsers are you seeing the problem on?
No response
Relevant log output
No response
Code of Conduct
The text was updated successfully, but these errors were encountered: