skip to Main Content

I have created a form with react hook form and did a validation with zod. In one input I want to write in numbers, when I write any number, the error says it is not a number:

<Controller
          name="calories"
          control={control}
          defaultValue={1}
          render={({ field }) => (
            <input
              {...field}
              type="number"
              className="w-full px-3 py-2 border rounded-md"
            />
          )}
 calories: z
    .number({
      required_error: "Calories is required",
      invalid_type_error: "Calories must be a number",
    })
    .int()
    .positive()
    .min(1, { message: "Calories should be at least 1" }),

I am missing something?

Did not find any solution to this

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution that was given from Ahmed Sbai from here End solution is this:

    calories: z.preprocess(
    (a) => parseInt(z.string().parse(a), 10),
    z.number().positive().min(1)
    ),
    

  2. When the input is of type number, it sends its value as a string even if the user inputs a number.
    As a result, Zod sees the value as a string and considers it invalid for the number() validation.

    I am not familiar with Zod but the idea here is that before applying the Zod validation, if you can, you’ll need to convert the input value to a number otherwise validate it as a string that should be a valid number have a look here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search