Home > Net >  how to correctly use Yup/formik number validation ReactJs
how to correctly use Yup/formik number validation ReactJs

Time:12-06

I would like to explain my problem of the day.

I'm using a simple number type validation

number: Yup.number()
.required("Required")
.max(100000000, "To big")
.min(0, "Not negative number")

my problem is ,in the entry of the field, I can add only one letter the "e", I do not understand why

example "12e3"

while I would like to enter only numbers

example "123"

if you have any ideas, thank you

Neff

CodePudding user response:

There is more than one way to achieve your only number input. The problem is not yup.

  1. check your input before sending. Exclude using ASCII
  2. check your input before sending. Exclude using Regex1 or Regex2
  3. change your input form type to number from basic html

CodePudding user response:

You can't handle it with Yup. because "e" interprets as number. in math "e" is a way to represent scientific notation. You can use react-number-format for handling this.

CodePudding user response:

Use this condition, it's take care of "e".

const digitsOnly = (value) => /^\d $/.test(value)

Yup.object().shape({
           mobile: Yup.string().required('please_enter_mobile').test('Digits only', 'digits_only', digitsOnly).min(7,'please_enter_valid_mobile').max(15, 'Maximum number limits')
        }).required()
  • Related