Yup: Yup.number() start with 0 problem

Created on 5 Aug 2019  路  5Comments  路  Source: jquense/yup

Hi,

I have specific problem, not sure if anyone experience the same.
If your field is type number and you want to do min / max on it and field start with 0 it is refused by Yup. You enter how ever 0 you want all are escaped.
For string it works well.

This is test case:

Yup.number().test({
      name: 'min',
      exclusive: true,
      params: 5 ,
      message:'some error message',
      test: value => {
        return value.length >= 5
      },
    })

Or even:

Yup.number().min(5, 'some error message')

Same goes for max as well.

Here is working example => https://codesandbox.io/s/vigorous-fire-e43j7
Pls try to add as much 0 as you want.

Expected:

I expect that max 3 of them is possible to be added.
I expect that Yup validate 0 as number.

Most helpful comment

I have done this way
Yup.object().shape({ inputFieldValue: Yup.string().length(6, 'Enter correct code').matches(/[0-9]+/gi, "Enter number only").required('Required') });

All 5 comments

@Milos5611 if you are trying to test whether the value is greater than equal to 5, you may want to change the test from:

      test: value => {
        return value.length >= 5
      },

to

      test: value => {
        return value >= 5
      },

I can give you more feedback if you post a complete example so that I can try to recreate the issue.

Hi @hdoupe ,

I am talking about length of value not if value is less or greater.

Hi @jquense can you please help with appropriate way of validation number length starting with 0 please ?

There is no way to test number length in yup. I've noted in past issues that, there is no good way to do that without locale/culture information which is out of scope for the library. There isn't any way that i know of in JS to stringify a number with leading zeros and maintain the zeros, If your starting with a string (like in a form) you can use access this.options.originalValue (be careful not to use an arrow function) in a custom test to get the input value, which may be a string

I have done this way
Yup.object().shape({ inputFieldValue: Yup.string().length(6, 'Enter correct code').matches(/[0-9]+/gi, "Enter number only").required('Required') });

Was this page helpful?
0 / 5 - 0 ratings