2

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>
Profer
  • 553
  • 8
  • 40
  • 81

2 Answers2

5
<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>
Sunny Khakse
  • 51
  • 1
  • 2
0
{
  ({ errors, ...others }) => (
  ...other components
  <button type="submit" disabled={isSubmitting || Object.keys(errors).length > 0}>
    Save
  </button> )
}
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Ajeet Shah Apr 30 '21 at 08:07