javascripthtmlformsvalidationdom-events

What event to listen for when a user clicks submit button in html5 invalid form?


I have a html5 form with html5 a required field. I want to catch the user interaction if the user submits the incomplete form and they are shown the the error message.

I thought I could use the invalid event, yet apparently it does not work.

How can I catch the invalid user interaction?

E.g.:

console.log('register event handler');

oninvalid = (event) => {
  console.log('it happened', event); // is not reached
};

addEventListener("invalid", (event) => {
  console.log('hallo'); // is not reached either
});
<form>
  <div class="group">
    <input type="text" />
    <label>Normal</label>
  </div>
  <div class="group">
    <input type="text" required />
    <label>Required</label>
  </div>
  <input type="submit" />
</form>


Solution

  • You need to set the useCapture argument of addEventListener() to true for it to be fired on the element the listener it was assigned to, as the invalid event does not bubble.

    document.addEventListener("invalid", () => {
      console.log('hallo');
    }, true);
    <form>
      <div class="group">
        <input type="text" />
        <label>Normal</label>
      </div>
      <div class="group">
        <input type="text" required />
        <label>Required</label>
      </div>
      <input type="submit" />
    </form>

    More information on useCapture and the event phases is available in this SO answer.