1

I am using formik library for my react project. I need to disable submit button initially when mandatory fields are empty or have any errors. I checked form status using below code.

const formik = useFormik(false);

        <Formik
        initialValues={!location.state ? InvoiceInitalValues : location.state}
        validationSchema={POValidation} innerRef={formRef}
        onSubmit={(form, actions, formikHelper) => {
          console.log(form);
          console.log(formRef);
          setTimeout(() => {
            saveInvoice(form, actions, formikHelper);
            actions.setSubmitting(false);
          }, 1000);
        }}
      >
        {({
          handleSubmit,
          handleChange,
          setFieldValue,
          values,
          handleReset,
          errors,
          resetForm, isSubmitting


        }) 

I console logged form status using but form is always 'isValid: True'. Please check below image. enter image description here

I printed it in the html also. but always isValid is True. I need to this for disable my button

printed status

 <p> {formik.isValid=== true ? "True" : "False"} </p>

I tried below code to disable my button

<Button className="btn btn-primary mr-1" type="submit" disabled={!formik.isValid}>

Submit

Why formik form validity is always true, even mandatory fields are empty. I spent more time to solve this. still could not fix this. Anyone know to fix this

1 Answer 1

5

You created form using Formik component, but you are checking isValid on another formik instance created through useFormik hook. That's not right.

You should use either <Formik> or useFormik.

As you have written code using Formik component. Here is how you access isValid property:

<Formik
  initialValues={!location.state ? InvoiceInitalValues : location.state}
  // ...
>
  {({
    values,
    handleChange,
    // ... 
    isValid // HERE
  }) => (
    <form onSubmit={handleSubmit}>
      <input
...

Here is a codesandbox.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried it also. but form isValid always true. when form load it should be false and submit button should be disable.
Beautiful !!! I applied to my project. Its working well. Thanks @Ajeet
@Kumara To achieve that You can pass a validateOnMount prop in the Formik wrapper to solve that.
@Kumara <Formik validateOnMount {...props}><Form /></Formik>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.