Skip to content

Commit

Permalink
feat: add support for root validation error
Browse files Browse the repository at this point in the history
With this change, `_root` is now a reserved key in `validationError` object. In some cases it's
useful to define a global validation error in your Zod schema, using `.superRefine(input, ctx)`,
without specifing a path in `ctx.addIssue()`. Now it's returned to the client, when defined.
  • Loading branch information
TheEdoRan committed Nov 27, 2023
1 parent 83b7cf8 commit b5b4ea8
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
9 changes: 5 additions & 4 deletions packages/next-safe-action/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@ export const createSafeActionClient = <Context>(createOpts?: {
const parsedInput = await schema.safeParseAsync(clientInput);

if (!parsedInput.success) {
const fieldErrors = parsedInput.error.flatten().fieldErrors as Partial<
Record<keyof z.input<typeof schema>, string[]>
>;
const { formErrors, fieldErrors } = parsedInput.error.flatten();

return {
validationError: fieldErrors,
validationError: {
_root: formErrors && formErrors.length ? formErrors : undefined,
...fieldErrors,
} as Partial<Record<keyof z.input<Schema> | "_root", string[]>>,
};
}

Expand Down
2 changes: 1 addition & 1 deletion packages/next-safe-action/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { z } from "zod";
export type SafeAction<Schema extends z.ZodTypeAny, Data> = (input: z.input<Schema>) => Promise<{
data?: Data;
serverError?: string;
validationError?: Partial<Record<keyof z.input<Schema>, string[]>>;
validationError?: Partial<Record<keyof z.input<Schema> | "_root", string[]>>;
}>;

/**
Expand Down

0 comments on commit b5b4ea8

Please sign in to comment.