Skip to content

Commit

Permalink
Merge pull request #101 from houseform/reset-errors
Browse files Browse the repository at this point in the history
[Fix] Reset field errors before run validations
  • Loading branch information
João Pedro Magalhães committed Apr 8, 2023
2 parents 66350dc 7680860 commit 495e693
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
41 changes: 41 additions & 0 deletions lib/form/form.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1664,3 1664,44 @@ test("Form `deleteField` should remove field", async () => {
rerender(<Comp />);
expect(queryByText("emailHere")).not.toBeInTheDocument();
});

test("Form submit should reset errors", async () => {
const submitMock = vi.fn();

const { getByText, queryByText, getByPlaceholderText } = render(
<Form onSubmit={submitMock}>
{({ submit, errors }) => (
<div>
<button onClick={submit}>Submit</button>
<Field<string> name="email" onSubmitValidate={z.string().min(1)}>
{({ value, setValue }) => (
<input
value={value}
placeholder="Email"
onChange={(e) => setValue(e.target.value)}
/>
)}
</Field>
{errors.map((error) => {
return <p key={error}>{error}</p>;
})}
</div>
)}
</Form>
);

await user.click(getByText("Submit"));

expect(
getByText("String must contain at least 1 character(s)")
).toBeInTheDocument();

await user.type(getByPlaceholderText("Email"), "emailhere");

await user.click(getByText("Submit"));

expect(
queryByText("String must contain at least 1 character(s)")
).not.toBeInTheDocument();
expect(submitMock).toHaveBeenCalledTimes(1);
});
9 changes: 8 additions & 1 deletion lib/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 347,11 @@ function FormComp<T extends Record<string, any> = Record<string, any>>(
const validArrays = await Promise.all(
formFieldsRef.current.map(async (formField) => {
const runValidationType = async (
type: "onChangeValidate" | "onSubmitValidate" | "onBlurValidate"
type:
| "onMountValidate"
| "onChangeValidate"
| "onSubmitValidate"
| "onBlurValidate"
) => {
const validator = formField.props[type as "onChangeValidate"];
if (!validator) return true;
Expand All @@ -362,6 366,9 @@ function FormComp<T extends Record<string, any> = Record<string, any>>(
if (type === "onSubmitValidate") formField._setIsValidating(false);
}
};
formField.setErrors([]);
const onMountRes = await runValidationType("onMountValidate");
if (!onMountRes) return false;
const onChangeRes = await runValidationType("onChangeValidate");
if (!onChangeRes) return false;
const onBlurRes = await runValidationType("onBlurValidate");
Expand Down

0 comments on commit 495e693

Please sign in to comment.