Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 621
k0pernikus Avatar asked Sep 01 '25 03:09

k0pernikus


1 Answers

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.

like image 155
Rory McCrossan Avatar answered Sep 02 '25 16:09

Rory McCrossan