formik
formik copied to clipboard
validateField does not validate nested field
Bug report
Current Behavior
As stated in the title, validateField
does not validate nested fields like user.name
.
Expected behavior
It should set the correct error.
Reproducible example
You can switch between the commented lines. This shows the difference between usage of validateField
with a not nested field and a nested one.
https://codesandbox.io/s/naughty-frost-013fk?file=/src/App.js
Suggested solution(s)
It took me soooo many hours when I encountered it till I realized that the bug might actually be in the Formik itself. I found that when the field error is set, it should use getIn(error, name)
instead of error[name]
. I'm gonna create a PR with a fix and a test.
diff --git a/packages/formik/src/Formik.tsx b/packages/formik/src/Formik.tsx
index d952a90..8b2d1b7 100755
--- a/packages/formik/src/Formik.tsx
+++ b/packages/formik/src/Formik.tsx
@@ -513,7 +513,7 @@ export function useFormik<Values extends FormikValues = FormikValues>({
.then((error: any) => {
dispatch({
type: 'SET_FIELD_ERROR',
- payload: { field: name, value: error[name] },
+ payload: { field: name, value: getIn(error, name) },
});
dispatch({ type: 'SET_ISVALIDATING', payload: false });
});
Your environment
Software | Version(s) |
---|---|
Formik | 2.2.6 |
React | 17.0.1 |
TypeScript | 4.2.4 |
Browser | Any |
npm/Yarn | npm 7.16.0 |
Operating System | MacOS 11 Big Sur |
Made a PR. Hopefully everything's correct, this is my first PR to Formik
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days
I don't want this to close, this one is important
I have the same issue at the moment. I am trying to use validateField
on an indexed field in an array like so: validateField("friends.2.name")
and it does nothing.
As fas as I can tell your fix would enable this as well, correct @jansedlon ?
Can someone please review, merge and release?
@silberistgold Havent tried that with arrays but if getIn
can deal with arrays then I'm pretty confident that it should work as well
+1
+1
+1
Would love to see this merged
+1
need this!!! how its going?
I also just get this problem in getIn
actually the only workaround that i found is validate the entire form instead of each field. its not very UX friendly anyways.
any ideas why this is not merged? This is really needed in an already painful workaround for formik not allowing validations of single field on blur, only the entire form. Now looks like we're having to do a workaround on a workaround, and it could be easily avoided with this one liner :(
Note: it appears this bug was fixed as of release 2.2.10, via #3783