0
votes

I have a form using Formik for my form with Yup for validation. Under each Field I have an <ErrorMessage /> component to display the relevant message for that form field. This works fine, however, since there are many fields, I would like to display a generic message beside the submit button when the user submits the form. Something like this:

<div className="alert alert-danger">
  One or more fields has an error.
</div>

I tried to conditionally render it based on the errors object from Formik:

{Object.keys(errors).length > 0 && (
  <div className="alert alert-danger">
    One or more fields has an error.
  </div>
)}

However when I onBlur any of the fields, all fields are validated internally, whether they have been touched or not, so as soon as I fill out the first form, this error message is rendered. How can I only render this message if the fields have been touched or are displaying an error message beside it?

1

1 Answers

0
votes

Since you only want to display the error message on submit, Formik has isValid and submitCount properties. Use those together to determine if the error message should be rendered:

{!isValid && submitCount > 0 && (
  <div className="alert alert-danger">
    One or more fields has an error.
  </div>
)}

This will cause it to only be rendered after the form has been submitted if there are any errors and will automatically disappear after all of the errors have been fixed.