Kevvv
Kevvv

Reputation: 4023

Formik Yup showing error even when it meets the requirement

I want the TextInput to validate exactly 16 digits. I've tried the following:

yup.number()
  .test('len', 'Must be exactly 16 numbers', val => val.length === 16)

But, every time I type anything into the field, I get the following:

Possible Unhandled Promise Rejection

I tried the following instead:

yup.number().max(16)

But, even when I input 16 digits exactly, it will still throw an error saying that it must be less or equal to 16 characters.

The updated the implementation:

<Formik
   initialValues={{ someInput: Number }}
   onSubmit={submitHandler}
   validationSchema={yup.object().shape({
   someInput: yup
       .number()
       .test('len', 'Must be exactly 16 numbers', val => val.toString().length === 16)
       .positive()
       .integer()
       .required(),
})>

Following is my TextInput

                                           <TextInput
                                                value={values.someInput}
                                                onChangeText={handleChange('someInput')}
                                                onBlur={() => setFieldTouched('someInput')}
                                                placeholder="some input"
                                                style={styles.someInput}
                                            />
                                            {touched.someInput && errors.someInput &&
                                                <Text style={{ fontSize: 10, color: 'red' }}>{errors.someInput}</Text>
                                            }

Upvotes: 0

Views: 1993

Answers (1)

Chris B.
Chris B.

Reputation: 5763

That's because numbers do not have a length property. You'd need to convert it to a string first. Also, checking for max on a number will error out on any number greater than 16, not a number more than 16 digits long.

yup.number()
  .test('len', 'Must be exactly 16 numbers', val => val.toString().length === 16)

Upvotes: 1

Related Questions