resolvers: ZodResolver error: "Expected number, received string"

The zodResolver example does not work as there is alway the following error.

{
  "age":{
    "message":"Expected number, received string",
    "type":"invalid_type"
  }
}

Here is a code sandbox to reproduce the error: https://codesandbox.io/s/react-hook-form-zod-resolver-example-forked-0p8rt?file=/src/App.js

Thanks for your reply/help.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 5
  • Comments: 19 (3 by maintainers)

Most upvoted comments

Coerce primitive values with Zod. Full example

const form = z.object({
    age: z
        .coerce    // SOLUTION
        .number(),
})

After a bit of digging around, i’ve discovered that the following achieves what i was looking for:

<input
  type="number"
  { ...register('myNumberField', { valueAsNumber: true } ) }  // <--- `valueAsNumber` is the solution here...
/>

@lailo If you won’t update to zod@beta v2 and don’t need to transform the value in number, you can do the following:

const schema = z.object({
  name: z.string(),
  age: z.string().refine((val) => !Number.isNaN(parseInt(val, 10)), {
    message: "Expected number, received a string"
  })
});

Hi @lailo , this is “normal” when using an input type="number", e.target.value is a string, to have a number, you should use e.target.valueAsNumber. You can find an answer here https://github.com/react-hook-form/resolvers/issues/62.

You’re right, the example does not work as expected, we have to update it 😃

Coerce primitive values with Zod. Full example

const form = z.object({
    age: z
        .coerce    // SOLUTION
        .number(),
})

This worked perfect for me, many thanks @omgismartinez

Coerce primitive values with Zod. Full example

const form = z.object({
    age: z
        .coerce    // SOLUTION
        .number(),
})

works, perfectly!

Coerce primitive values with Zod. Full example

const form = z.object({
    age: z
        .coerce    // SOLUTION
        .number(),
})

You saved my time. Thanks!