8000 feat: add multiple errors by moh3n9595 · Pull Request #19 · MrBr/antd-zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: add multiple errors #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 10, 2025
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
6 changes: 3 additions & 3 deletions src/utils/createSchemaFieldRule.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe("createSchemaFieldValidator", () => {

await expect(
rule(formInstance).validator?.(fieldRule, {}, () => {}),
).rejects.toEqual("Required");
).rejects.toEqual(["Required"]);
});
it("should validate successfully NestedRefinedSchema values", async () => {
const rule = createSchemaFieldRule(NestedRefinedSchema);
Expand All @@ -46,7 +46,7 @@ describe("createSchemaFieldValidator", () => {

await expect(
rule(formInstance).validator?.(fieldRule, {}, () => {}),
).rejects.toEqual("Required");
).rejects.toEqual(["Required"]);
});
it("should reject invalid NestedRefinedSchema values", async () => {
const rule = createSchemaFieldRule(NestedRefinedSchema);
Expand All @@ -55,6 +55,6 @@ describe("createSchemaFieldValidator", () => {

await expect(
rule(formInstance).validator?.(fieldRule, {}, () => {}),
).rejects.toEqual("Must be Luka");
).rejects.toEqual(["Must be Luka"]);
});
});
20 changes: 17 additions & 3 deletions src/utils/formatErrors.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import z from "zod";
import z, { ZodError, ZodIssue } from "zod";
import formatErrors from "./formatErrors";
import prepareValues from "./prepareValues";

const fakeIssues: ZodIssue[] = [
{ code: "custom", message: "Error one", path: ["field"] },
{ code: "custom", message: "Error two", path: ["field"] },
];

const fakeZodError = new ZodError(fakeIssues);

const schema = z.object({ field: z.string() });

describe("formatErrors", () => {
it("should return empty errors", async () => {
const schema = z.object({
Expand All @@ -27,7 +36,7 @@ describe("formatErrors", () => {
}
const formattedErrors = formatErrors<{}>(schema, res.error);

expect(formattedErrors).toEqual({ prop: "Required" });
expect(formattedErrors).toEqual({ prop: ["Required"] });
});
it("should format nested prop.child error", async () => {
const schema = z.object({
Expand All @@ -42,6 +51,11 @@ describe("formatErrors", () => {
}
const formattedErrors = formatErrors<{}>(schema, res.error);

expect(formattedErrors).toEqual({ "prop.child": "Required" });
expect(formattedErrors).toEqual({ "prop.child": ["Required"] });
});
it("should return multiple errors", () => {
const formattedErrors = formatErrors(schema, fakeZodError);
console.log(formattedErrors)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the log

expect(formattedErrors).toEqual({ field: ["Error one", "Error two"] });
});
});
10 changes: 7 additions & 3 deletions src/utils/formatErrors.ts
10000
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import getIssueAntdPath from "./getIssueAntdPath";
const formatErrors = <T extends ZodRawShape>(
schema: ZodTypeAny,
errors: ZodError<T>,
): { [key: string]: string } => {
): { [key: string]: string[] } => {
if (errors.issues.length === 0) {
return {};
}
Expand All @@ -22,14 +22,18 @@ const formatErrors = <T extends ZodRawShape>(
(formattedErrors, issue) => {
try {
const path = getIssueAntdPath(schema, issue);
formattedErrors[path] = issue.message;
if (formattedErrors[path]) {
formattedErrors[path].push(issue.message);
} else {
formattedErrors[path] = [issue.message];
}
} catch (e) {
console.warn(e);
}

return formattedErrors;
},
{} as { [key: string]: string },
{} as { [key: string]: string[] },
);
};

Expand Down
12 changes: 6 additions & 6 deletions src/utils/validateFields.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,36 @@ describe("validateFields", () => {
});
it("should return errors", async () => {
expect(await validateFields(NameSchema, {})).toEqual({
name: "Required",
name: ["Required"],
});
});
it("should return errors for nested schemas", async () => {
expect(await validateFields(NestedRefinedSchema, {})).toEqual({
"user.name": "Required",
"user.name": ["Required"],
});
});
it("should return errors for primitive array field", async () => {
expect(await validateFields(ArrayNumberFieldSchema, {})).toEqual({
numbers: "Required",
numbers: ["Required"],
});
});
it("should return errors for object array field", async () => {
expect(
await validateFields(ArrayUserFieldSchema, { users: "invalid value" }),
).toEqual({
users: "Expected array, received string",
users: ["Expected array, received string"],
});
});

it("should return errors for object array field items", async () => {
expect(await validateFields(ArrayUserFieldSchema, { users: [1] })).toEqual({
"users.0": "Expected object, received number",
"users.0": ["Expected object, received number"],
});

expect(
await validateFields(ArrayUserFieldSchema, { users: [{ name: 10 }] }),
).toEqual({
"users.0.name": "Expected string, received number",
"users.0.name": ["Expected string, received number"],
});
});
});
4 changes: 2 additions & 2 deletions src/utils/validateFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import formatErrors from "./formatErrors";
const validateFields = async <T extends ZodRawShape>(
schema: AntdFormZodSchema<T>,
values: {},
): Promise<{ [key: string]: string }> => {
): Promise<{ [key: string]: string[] }> => {
const valuesWithPlaceholders = prepareValues(schema, values);

const res = await schema.safeParseAsync(valuesWithPlaceholders);

if (res.success) {
return {} as Record<keyof T, string>;
return {} as Record<k 6D4E eyof T, string[]>;
}

return formatErrors(schema, res.error);
Expand Down
4 changes: 4 additions & 0 deletions stories/basic.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const Child = z.object({
});

const BasicSchema = z.object({
email: z.string().email().min(5).max(15).includes('.com'),
name: z.string().refine((value) => value.length > 2, {
message: "Must have more than 2 chars",
}),
Expand All @@ -46,6 +47,9 @@ const rule = createSchemaFieldRule(BasicSchema);
const BasicForm = () => {
return (
<Form>
<Form.Item label="Enter email" name="email" rules={[rule]}>
<Input />
</Form.Item>
<Form.Item label="Enter name" name="name" rules={[rule]}>
<Input />
</Form.Item>
Expand Down
0