Disable button till all the form fields get filled in Formik

Viewed 4144

I am using Formik form. I have two fields inside it. I need to disable the save button till both the fields get filled.

<Formik initialValues={initialValues} validationSchema={validate} onSubmit={() => this.handleSubmit()}>
  {({ values, handleChange, handleSubmit, setValues, isSubmitting }) => (
    <form onSubmit={handleSubmit} noValidate>
      <div>
        <div onClick={this.showDrawer}>
          <h6>Select Company </h6>
          <input name="customer" readOnly placeholder="Select" value={values.customer} type="text" />
        </div>
        <ErrorMessage component="span" name="customer" />
      </div>
      <div>
        <div onClick={this.showDrawer}>
          <h6>Select Driver</h6>
          <input name="driver" readOnly placeholder="Select" value={values.driver} type="text" />
        </div>
        <ErrorMessage component="span" name="driver"/>
      </div>
      <button type="submit" disabled={isSubmitting}>
        Save
      </button>
    </form>
  )}
</Formik>
2 Answers
<Formik initialValues={initialValues} validationSchema={validate} onSubmit={() => this.handleSubmit()}>
  {({ values, handleChange, handleSubmit, setValues, isSubmitting, dirty, isValid }) => (
    <form onSubmit={handleSubmit} noValidate>
      <div>
        <div onClick={this.showDrawer}>
          <h6>Select Company </h6>
          <input name="customer" readOnly placeholder="Select" value={values.customer} type="text" />
        </div>
        <ErrorMessage component="span" name="customer" />
      </div>
      <div>
        <div onClick={this.showDrawer}>
          <h6>Select Driver</h6>
          <input name="driver" readOnly placeholder="Select" value={values.driver} type="text" />
        </div>
        <ErrorMessage component="span" name="driver"/>
      </div>
      <button type="submit" disabled={!(dirty && isValid)}>
        Save
      </button>
    </form>
  )}
</Formik>
{
  ({ errors, ...others }) => (
  ...other components
  <button type="submit" disabled={isSubmitting || Object.keys(errors).length > 0}>
    Save
  </button> )
}
Related