Yup: Yup.number() can not properly convert empty string into 0

Created on 18 Sep 2019  路  3Comments  路  Source: jquense/yup

Describe the bug
I'm using Yup with Formik for validating my input. for some reason. Yup.number inside a Yup.array.of(Yup.shape({...})) will not correctly convert an empty string '' to 0 instead of a NaN value, so 'must be a number ' error shows up. It's strange that Yup.number outside Yup.array.of(Yup.shape({...}) works just fine.

To Reproduce
I created this codeSandBox to reproduce this error. In that, I have two number value, one outside array, another inside array. both of them are required. When I touch but not change the value of the number field outside an array, Yup show require error correctly, then I do the same thing to the number field inside an array, it shows up "must be a number type, but the final value was: NaN"
https://codesandbox.io/embed/yup-number-is-nan-bug-1y29v?fontsize=14

Expected behavior
I expect the validation for number works the same whether in an array or not.

Platform (please complete the following information):

  • Browser chrome
  • Version 77.0.3865.75

Additional context
Add any other context about the problem here.

Most helpful comment

You can transform the value like this:

Yup.object().shape({
      no: Yup
             .number()
             .transform(value => (isNaN(value) ? undefined : value)) <---
             .required("can not be empty")
    })

All 3 comments

You can transform the value like this:

Yup.object().shape({
      no: Yup
             .number()
             .transform(value => (isNaN(value) ? undefined : value)) <---
             .required("can not be empty")
    })

You can transform the value like this:

Yup.object().shape({
      no: Yup
             .number()
             .transform(value => (isNaN(value) ? undefined : value)) <---
             .required("can not be empty")
    })

This is what I did to solve this issue actually. but I still want to know why auto transform failed. could it be considered as a bug?

It's not a bug an empty string isn't a number, yup is intentionally stricter than normal JS coercion.

Was this page helpful?
0 / 5 - 0 ratings