jaredpalmer / formik

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

How to show an additional error message when validation fails on submit #1294

Open awakened23 opened 5 years ago

awakened23 commented 5 years ago

❓Question

I need to show an additional error message if validation fails on submit. This error message should not be displayed if validation fails on change/ on blur. Looks like there is no way to tell if the validation errors happen on submit since the validate function is called on change, blur and submit. The validation that happens on change/blur can be disabled so that I know the errors happen on submit but I need the validation to happen on change and blur as well.

Here is what I did:

<Formik
  validate={values => {
    const errors = {};

    if(!values.reason){
      errors.reason = 'This is required';
    }
    return errors;
  }}
>
  {{errors, status, setStatus, validateForm} => (
    <Form>
      {status && <div>There was a problem submitting the form</div>}
      <Field type="text" name="reason"/>
      <ErrorMessage name="reason" />
      <button type"submit" onClick={() => {
        validateForm().then(errors => {
          if(Object.keys(errors).length > 0){
            setStatus('error');
          }
        });
      }}>
        Submit
      </button>
    </Form>
  )}  
</Formik>

This works but the validate function is run twice when the submit button is clicked. Is there a better way to do this?

jaredpalmer commented 5 years ago

Not at the moment. This is something to consider for us to consider for v2

bratva commented 5 years ago

Yes, i need to different validation on change from validation on submit. When i have validation from change, i want to validate only touched fields, but before submit - want to validate all fields

Possible Solution: add the source props to validation. Where source is 'change' | 'blur' | 'submit' | string

TaylorDale commented 5 years ago

Good answer at https://github.com/jaredpalmer/formik/issues/1484#issuecomment-490558973

Cryfear commented 4 years ago

lol no answer, :(((

github-actions[bot] commented 3 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days