Yup - comma decimal separator instead of dot

Viewed 5130

I'm using a simple Yup schema like this to validate a Formik input field in React Native:

Yup.number().positive()

My users are going to use the comma separator for decimals, so I need the schema to throw an error for values such as 1.35 and accept values like 1,35. Using a regex seems off the table as the matches method is only available for strings.

2 Answers

After tinkering a bit with transform, this what ended up working for me:

Yup.number()
   .transform((_, value) => {
      if (value.includes('.')) {
        return null;
      }
      return +value.replace(/,/, '.');
    })
    .positive(),

I am not aware of a function in Yup to be able to parse number in different formats. But one easy way is to transform/replace the comma by nothing so it become a number

number().transform((o, v) => parseInt(v.replace(/,/g, '')))

This way your number 10,000 become 10000 and is indeed a valid number.

On the other hand 10.000 stay 10.000 and is not valid.

Related