Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Invalid event capturing

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(''));
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda