Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an asynchronous validation when I use superRefine method in zod

Tags:

zod

node.js

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"]
        })
    }

})
like image 835
Emanuek Avatar asked Sep 18 '25 11:09

Emanuek


1 Answers

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]" })
like image 187
robinvdvleuten Avatar answered Sep 21 '25 03:09

robinvdvleuten