I just want to check if this is a suitable use-case for using { capture: true } or if there is a different 'best practise' way of doing things.
I have a HTML page which contains a form and multiple dynamic number inputs.
The default message of Please enter a valid value. The two nearest valid values are 4 and 8. is not really suitable, so I would like to customise it.
I first tried something like:
document.addEventListener('invalid', ({ target }) =>
target.setCustomValidity('Hours must be either 0, 4 or 8.'));
document.addEventListener('input', ({ target }) =>
target.setCustomValidity(''));
It appears this doesn't work because the invalid event doesn't bubble.
Next was this:
const hoursElements = Array.from(document.querySelectorAll('input[type="number"]'));
hoursElements.forEach((element) =>
element.addEventListener('invalid', ({ target }) =>
target.setCustomValidity('Hours must be either 0, 4 or 8.')));
hoursElements.forEach((element) =>
element.addEventListener('input', ({ target }) =>
target.setCustomValidity('')));
However, since the page is dynamic, I would need to keep calling the above whenever new inputs were added.
I finally found this which works:
const invalidEvent = ({ target }) =>
target.setCustomValidity('Hours must be either 0, 4 or 8.');
document.addEventListener('invalid', invalidEvent, { capture: true });
document.addEventListener('input', ({ target }) =>
target.setCustomValidity(''));