Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a method of writing custom errors on number requirements in a zod schema?

I'm using zod and react hook form to validate a number input, when the input is empty, I'm given the error "Expected number, received NaN" is there a way to override this error with a custom one?

This is my zod schema:

import { z } from "zod";

export const newTransactionSchema = z.object({
  title: z
    .string()
    .min(1, "Title Must Be Atleast 1 Character")
    .max(10, "Title Must Be No Longer Than 10 Characters"),
  amountSpent: z.number().positive("Please Enter An Expense Greater Than 0"),
  description: z
    .string()
    .min(8, "Description Must Be At Least 8 Characters")
    .max(25, "Description Must Be No Longer Than 25 Characters"),
});

export type TNewTransaction = z.infer<typeof newTransactionSchema>;

the input:

<label htmlFor="amountSpent">Amount Spent</label>
   <input
     type="number"
     className="mt-2 rounded-md border border-[#3a3a3a] bg-[#0A0A0A] px-2 py-1 text-white outline-none focus:border-[#3a3a3a] focus:ring-2 focus:ring-[#3a3a3a] focus:ring-offset-2 focus:ring-offset-black"
     id="amountSpent"
     {...register("amountSpent", { valueAsNumber: true })}
   />
  <span className="mb-3 font-medium text-rose-500">
    {errors?.amountSpent?.message}
  </span>

I tried passing a string into the .number() property but it doesn't accept parameters.

like image 648
itsjames212 Avatar asked Oct 31 '25 05:10

itsjames212


1 Answers

z.number accepts an object input, not a string input, you can check the docs here: https://github.com/colinhacks/zod#numbers

For your case, I'd do something like this:

z.number({ invalid_type_error: 'You got it wrong mate!' }).positive('etc.')

Here is the z.number api that my code editor is claiming - make sure you have the latest version if you're not seeing this.

enter image description here

like image 88
Gus Bus Avatar answered Nov 02 '25 23:11

Gus Bus