Skip to content
This repository has been archived by the owner on Jul 27, 2022. It is now read-only.

Commit

Permalink
Fix(useForm): when running field validation with nested field(s), err…
Browse files Browse the repository at this point in the history
…or results will be overrided by the last field
  • Loading branch information
wellyshen committed Mar 28, 2021
1 parent d00ec9b commit cf7980f
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/hungry-pants-play.md
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions src/useForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) => (
<>
<input
name="foo.a"
ref={field((val: string) => (!val.length ? errors.foo.a : false))}
/>
<input
name="foo.b"
ref={field((val: string) => (!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({
Expand Down
2 changes: 1 addition & 1 deletion src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ export default <V extends FormValues = FormValues>({

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;
}, {})
);
Expand Down

0 comments on commit cf7980f

Please sign in to comment.