From cf7980f72790bc6f5a95192fff629ec909ab38ad Mon Sep 17 00:00:00 2001 From: Welly Shen Date: Sun, 28 Mar 2021 15:36:45 +0800 Subject: [PATCH] Fix(useForm): when running field validation with nested field(s), error results will be overrided by the last field --- .changeset/hungry-pants-play.md | 5 +++++ src/useForm.test.tsx | 21 +++++++++++++++++++++ src/useForm.ts | 2 +- 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 .changeset/hungry-pants-play.md diff --git a/.changeset/hungry-pants-play.md b/.changeset/hungry-pants-play.md new file mode 100644 index 00000000..edd8de63 --- /dev/null +++ b/.changeset/hungry-pants-play.md @@ -0,0 +1,5 @@ +--- +"react-cool-form": patch +--- + +Fix(useForm): when running field validation with nested field(s), error results will be overrided by the last field diff --git a/src/useForm.test.tsx b/src/useForm.test.tsx index b19d496d..d0b0d0bb 100644 --- a/src/useForm.test.tsx +++ b/src/useForm.test.tsx @@ -1076,6 +1076,27 @@ describe("useForm", () => { } ); + it("should run field-level validation with nested fields", async () => { + const errors = { foo: { a: "Required", b: "Required" } }; + renderHelper({ + onError, + children: ({ field }: Methods) => ( + <> + (!val.length ? errors.foo.a : false))} + /> + (!val.length ? errors.foo.b : false))} + /> + + ), + }); + fireEvent.submit(getByTestId("form")); + await waitFor(() => expect(onError).toHaveBeenCalledWith(errors)); + }); + it("should run field-level validation with dependent fields", async () => { const errors = { foo: "Bar is required" }; renderHelper({ diff --git a/src/useForm.ts b/src/useForm.ts index 57a081b8..f64c1e04 100644 --- a/src/useForm.ts +++ b/src/useForm.ts @@ -487,7 +487,7 @@ export default ({ return Promise.all(promises).then((errors) => Object.keys(fieldValidatorsRef.current).reduce((acc, cur, idx) => { - acc = { ...acc, ...(errors[idx] ? set({}, cur, errors[idx]) : {}) }; + acc = { ...acc, ...(errors[idx] ? set(acc, cur, errors[idx]) : {}) }; return acc; }, {}) );