#useForm validation using zod (async refine?)

3 messages · Page 1 of 1 (latest)

crude bison
#

Hi,

I'm using Mantine's useForm + Zod for validation and I would like to use Zod's async refine method as part of my form's schema. Users in my app can only register if they have a valid registration code. So I want to refine the form's code field to query my database whether that code is valid. Which I can't, as it appears Mantine's zodResolver uses the sync version of zod's parse method.

Is that right? If not, how can I work around this limitation?

The zod schema:

const formSchema = z.object({
    first_name: z
      .string()
      .min(2, { message: "..." }),
    last_name: z
      .string()
      .min(2, { message: "..." }),
    email: z
      .string()
      .email({ message: "..." })
      .refine(
        async () => {
          const { data: emailExists } = await checkEmailExists();
          return !emailExists;
        },
        {
          message: "A user with this email already exists",
        }
      ),
    code: z
      .string({
        errorMap: () => ({
          message: "...",
        }),
      })
      .refine(
        async () => {
          const { data: isValid } = await validateRegistrationCode();
          return isValid;
        },
        {
          message:
            "Invalid code. Make sure the code was correctly inserted",
        }
      ),
  });

The form:

const form = useForm({
    validate: zodResolver(formSchema),
    validateInputOnBlur: ["first_name", "last_name", "email"],
    initialValues: {
      first_name: "",
      last_name: "",
      email: "",
      code: "",
    },
    transformValues: (values) => ({
      ...values,
      name: `${values.first_name} ${values.last_name}`,
    }),
  });

Thanks in advance

ocean leaf
cinder stirrup