sveltekit-superforms icon indicating copy to clipboard operation
sveltekit-superforms copied to clipboard

Error when using `.optional()` with `.refine()` with Zod

Open Ennoriel opened this issue 1 year ago • 3 comments

  • [x] Before posting an issue, read the FAQ and search the previous issues.

Description On a zod schema, when using .optional() with .refine(), the method superValidate(zod(schema) fails with error:

Async refinement encountered during synchronous parse operation. Use .parseAsync instead.

If applicable, a MRE

// file: +page.server.ts
import { superValidate } from "sveltekit-superforms/server";
import { zod } from "sveltekit-superforms/adapters";
import { z } from "zod";

const schema = z.object({
  name: z.string().min(1),
  email: z
    .string()
    .optional()
    .refine(async () => Promise.resolve(true)),
});

export const load = async () => {
  return { form: await superValidate(zod(schema)) };
};
// file: +page.svelte
// empty, not even implemented

Ennoriel avatar Apr 10 '24 12:04 Ennoriel

That is strange, since safeParseAsync is used in the adapter. Does it work when you remove optional?

ciscoheat avatar Apr 12 '24 01:04 ciscoheat

Thank you for your message :)

Yes, it works when removing .optional()

Ennoriel avatar Apr 15 '24 07:04 Ennoriel

It looks like a problem with Zod and the JSON Schema generator: https://github.com/colinhacks/zod/issues/1460

ciscoheat avatar Apr 23 '24 14:04 ciscoheat