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.
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.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With