jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.97k stars 2.79k forks source link

How to validate the form on enableReinitialize or mapPropsToValues #1439

Open mjangir opened 5 years ago

mjangir commented 5 years ago

I'm filling up the initial values from redux using mapPropsToValues and enableReinitialize: truebut this is not working as expected when it comes to validate the form. If its a create only form, we can simply call this.props.validateForm in componentDidMount. This will fill errors object if there are any errors in the form. But how to validate the form once its values have been populated from redux (mapPropsToValues)?

I tried using the following:

componentWillReceiveProps(props) {
    if (this.props.fetchState === 'loading' && props.fetchState === 'data') {
      setTimeout(() => this.props.validateForm(), 500);
    }
  }

But this doesn't seem to be a good solution to me as well as I have to use timeout otherwise it validates the form before the mapPropsToValue is actually used.

satsuya0114 commented 5 years ago

@mjangir

You can try isInitialValid in property

krnlde commented 5 years ago

How to do that in the future since isInitialValid will deprecated?

dtilchin commented 5 years ago

How to do that in the future since isInitialValid will deprecated?

I'm also interested in an answer on this. The use case is, how to make a submit button initially disabled when a type="file" input is required.

mac89 commented 3 years ago

A bit late but using the following worked for me, using Yup for the validationSchema. Set initialTouched to true for the ones you want validated. An empty object for initialErrors seems sufficient. Lastly setting validateOnMount to true is required for revalidation to occur.

    <Formik
      initialValues={initialValues}
      onSubmit={submit}
      validationSchema={object(schemaShape)}
      enableReinitialize={true}
      initialTouched={{ configCheck: true, installedDate: true, country: true }}
      initialErrors={{}}
      validateOnMount={true}
    >
jvnlwn commented 3 years ago

Confirming that the combination of enableReinitialize and validateOnMount does cause <Formik /> to revalidate.