Martin Muzatko
Martin Muzatko

Reputation: 326

Invalid eventListener for forms

I'm trying to catch the invalid event for forms, but it doesn't seem to happen?

https://codepen.io/MartinMuzatko/pen/VzWwxG?editors=1010

For my use case, I need to have the listener on the form (for asynchronous form validation). So attaching the listener to individual inputs is not an option for me.

According to the spec, forms should fire an invalid event when some of the input is invalid.

https://www.w3.org/TR/html5/forms.html#client-side-form-validation

Upvotes: 4

Views: 8911

Answers (1)

Devesh Sati
Devesh Sati

Reputation: 676

The 'invalid' event is not "bubbled" . It fires on the specific input element which is invalid and won't bubble up to the form element. You need to attach the listener on the input element.

var input = document.querySelector('form input')

input.addEventListener('invalid', (e)=>{
    console.log('invalid')
});

Updated pen: https://codepen.io/theLufenk/pen/WEONBw?editors=1010

Or if you want to catch the event at form level, you will have to use event capturing.

var form = document.querySelector('form')

form.addEventListener('invalid', (e)=>{
    console.log('invalid')
},true)

Update Pen: https://codepen.io/theLufenk/pen/Ojgmxz?editors=1011

Upvotes: 13

Related Questions