Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React hook form and zod inumber input

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading