Next.js Discord

Discord Forum

Why zod not validating form values?

Answered
Rex posted this in #help-forum
Open in Discord
Avatar
RexOP
i have a dropdown and based on its value I want to apply schema validation. When the stockType is "bought" I don't want to check for the "jobcard"
here is the code
const baseSchema = z.object({
  stockType: z.string(),
  quantity: z.coerce.number().min(1).positive().int().max(1000),
});

const mySchema = z.discriminatedUnion("stockType", [
  z
    .object({
      stockType: z.literal("bought"),
      supplier: z.string().min(1, { message: "too small" }),
      invoiceNo: z.string().min(1, { message: "to small" }),
    })
    .merge(baseSchema),
  z
    .object({
      stockType: z.literal("returned"),
      jobCard: z.string().min(2),
      returnedBy: z.string().min(1),
    })
    .merge(baseSchema),
]);

const AddStockDialog = ({ item }: { item: Product }) => {
  const { mutate } = useSWRConfig();
  const { itemCode, id: productId, categoryId, quantity } = item;

  const API_URL_RETURNED = `/api/products/${productId}`;
  const API_URL_BOUGHT = `/api/product/${productId}/add-stock`;

  const [open, setOpen] = useState(false);

  const [supplierOpen, setSupplierOpen] = useState(false);

  const form = useForm({
    resolver: zodResolver(mySchema),
    defaultValues: {
      quantity: 1,
      stockType: "bought",
      supplier: "",
      invoiceNo: "",
      jobCard: "",
      returnedBy: "",
    },
  });

  const stockType = form.watch("stockType");
  const allValues = form.watch();

  const { isSubmitting, isValid } = form.formState;

  const onSubmit = async (values: z.infer<typeof mySchema>) => {
    try {
      const apiUrl =
        values.stockType === "bought" ? API_URL_BOUGHT : API_URL_RETURNED;
      await axios.post(apiUrl, { ...values });
      mutate(`/api/categories/${categoryId}`);

      setOpen(false);
      console.log("submitted");
    } catch (error) {
      console.log("ERROR: ", error);
      toast.error("Error adding items to stock");
    }
  };

Any help what might be causing the issue?
Answered by Rex
Ok I have it working I removed the stockType from the baseSchema
View full answer

2 Replies

Avatar
RexOP
Ok I have it working I removed the stockType from the baseSchema
Answer
Avatar
RexOP
and it works