I'm trying to use an asynchronous validation on superRefine in zod but I got this error: Async refinement encountered during synchronous parse operation. Use .parseAsync instead
.
I'm trying to register an user. I'm using prisma as a database access.
import { prisma } from '../../../helper/prisma'
import { z } from 'zod'
export const registerSchema = z.object({
email: z.string().min(1, {
message: "Email field is required"
}).trim().email({
message: "Email is invalid"
}),
password: z.string().min(7, {
message: "Password must have more than 6 characters"
}).trim(),
confirm: z.string().trim().min(1, {
message: "Confirm password field is required"
})
}).superRefine(async ({ password, confirm, username, email }, ctx) => { // Set asynchronous validation
const emailExists = await prisma.user.findUnique({ // This does not work
where: {
email
}
})
if (emailExists) {
ctx.addIssue({
code: "custom",
message: "The email already exists",
path: ["email"]
})
}
})
The error means that you try to parse you schema synchronously, which won't work anymore as you now have an asynchronous validation.
So instead of parsing your schema like this
registerSchema.parse({ email: "[email protected]" })
You need to call it like this
await registerSchema.parseAsync({ email: "[email protected]" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With