Listen to ‘onInvalid’ HTML event for a

I would like to add an event listener for when a user tries to submit a <form> that has validation errors.

Is there a way to do that in a reliable and accessible way?

Solutions I considered (none of them are good):

  1. Adding ‘submit’ event listener to <form>.

    This doesn’t work since ‘submit’ is only fired for valid forms.

  2. An ‘invalid’ event is fired by HTML <input> elements that have validation errors when
    the user tries to submit a form.

    The event does not bubble, so I can’t listen to it like this: form.addEventListener('invalid', callback);

    Thus, listening for ‘invalid’ event requires adding ‘invalid’ event listener for each <input> inside the form when that field is created. It is easy to forget to add an event listener to a field, since fields are created dynamically in many different .js and .tsx files, thus this solution is error-prone and far from ideal.

  3. Listening for ‘click’ event on the submit button and in the callback checking if form.checkValidity() is false.

    This solution is also not ideal as screen reader software and other assistive technologies won’t necessarily trigger the ‘click’ event when trying to submit the form.

Is there any good way to know if a user tries to submit an invalid form?

I am fine with a solution that involves React, jQuery or native JavaScript.


If there is no good to this problem, please consider my use case and tell if there is an alternative approach:

I need to add styling to invalid form fields only after the user tried to submit a form.