formik: 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 |
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 8
- Comments: 15 (4 by maintainers)
I don’t want this to close, this one is important
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 😦
Made a PR. Hopefully everything’s correct, this is my first PR to Formik
Note: it appears this bug was fixed as of release 2.2.10, via #3783