Search code examples
reactjsreact-final-form

Display an alert if the form has errors on submit in react-final-form


I'm using react-final-form and I would like to display an alert if a user tries to submit a form with errors. But I don't know how to do it. I've made a function for form onSubmit like this:

onSubmit={event => {
  event.preventDefault();
  //How to check if the form has any validation  errors?
  if () {
    alert("Errors");
  } else {
    handleSubmit();
  }
}}

How can I check in it if there are any validation errors? Here is my codesandbox.


Solution

  • There are lots of possible ways to do it. Here's one:

    <form
      onSubmit={event => {
        if (invalid) {
          alert(JSON.stringify(errors, undefined, 2));
        }
        handleSubmit(event);
      }}
    >
      ...fields
    </form>
    

    Edit React Final Form - Synchronous Record Level Validation