Formik button not disabled initially

Viewed 761

I am using Formik validation and I am trying to disable the button if the validation schema is not fulfilled. It's supposed to be a phone number so if I type alphabets, the button is disabled. It works.

However, initially when I open the screen and the text field is empty, the button should still be disabled. But it's not. Even though the validation schema says 'required'. How can I fix this?

<Formik
              initialValues={initialValues}
              onSubmit={handleSubmitForm}
              validationSchema={validationSchema}>
              {({ handleChange, handleBlur, handleSubmit, values, isValid }) => (
                <View style={styles.searchFieldContainer}>
                  <View style={styles.form}>
                    <FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />
                    <ErrorMessage
                      name="phoneNumber"
                      render={(msg) => (
                        <Text style={styles.errorText}>{msg}</Text>
                      )}
                    />
                  </View>
                  <View style={styles.buttonContainer}>
                <Button
                  block
                  success
                  disabled={!isValid}
                  onPress={handleSubmit}
                  style={styles.button}>
                  <Text>Speichern</Text>
                </Button>
                  </View>
                </View>
              )}
            </Formik>
const phoneNumberValidationSchema = yup.object().shape({
  phoneNumber: yup
    .string()
    .label('phoneNumber')
    .required('Bitte gebe deine Handynummer ein.')
    .matches(/^[0-9]*$/, 'Bitte nur Ziffern eingeben.'),
});
1 Answers

Try setting the isInitialValid prop on the Formik component to false.

<Formik
  initialValues={initialValues}
  onSubmit={handleSubmitForm}
  validationSchema={validationSchema}
  isInitialValid={false}
>
  ...
</Formik>
Related