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

Fix(useForm): when running field-level validation with nested field(s), the last field will overrides the error results #518

Merged
merged 1 commit into from
Mar 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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