TanStackT
TanStack8mo ago
6 replies
naughty-peach

Form not submitting when adding onChange zod validator

I'm trying to add zod (v4) schema validation on the boundary between my forms/trpc interface. When I add an onChange validator my form stops submitting, the form state appears to think it's submitting since canSubmit transitions to false in the form.Subscribe, however, the onSubmit callback doesn't get called. When I remove the onChange validator in place of manually calling zodSchema.parse() in the onSubmit is called, the schema validated, and my rpc executes.

Any ideas on how to debug this or what I'm doing wrong?

  const form = useForm({
    defaultValues: {
      email: user!.email,
      first_name: profile?.first_name || "",
      last_name: profile?.last_name || "",
      job_title: profile?.job_title || "",
      target_market: "",
      note: getInitialNote(leadType, contextInfo),
      type: leadType,
    },
    validators: {
      onChange: SubmitLeadSchema,
    },
    // this doesn't execute unless onChange is removed
    onSubmit: async ({ value }) => {
      try {
        console.log("inside try")
        const res = SubmitLeadSchema.parse({ ...value, brand_id: brandId });
        console.log(res)
        await trpc.leads.submit.mutate({ ...value, brand_id: brandId });
        onClose();
        toast.success("Your request has been sent to the brand!");
      } catch (error) {
        if (error instanceof TRPCError) {
          console.error(error);
          return;
        }
        if (error instanceof Error) {
          console.error(error);
          return;
        }
        console.error(error);
        return;
      }
    },
  });
Was this page helpful?