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

226
Visualizações
How to validate KeyboardEvent values for a number input?

I am having an input of type number. Chromium browsers seems to restrict the input too, however firefox doesn't and this is a problem (for our product managers). So I figured out, why not filtering while having an input via an event like Keydown, Keyup or Keypress.

I first made this function to filter my input:

public filterInput(event: KeyboardEvent){
    //ignore all characters that are not numbers, except backspace, delete, left arrow and right arrow
    if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) {
        event.preventDefault();
    }
}

However I am thinking of generalizing this function and make it something like this

public filterInput(event: KeyboardEvent, regExPattern: string | RegExp){
    const keyCodesArray: Array<number> = [..., 8, 46, 37, 39]; //get all possible keyCodes in that pattern + allow right/left arrows, backspace and delete
    //check whether keycode is included or not. 
    if (!keyCodesArray.includes(event.keyCode)) {
        event.preventDefault();
    }
}

After searching and digging into it I came up with such a general function:

public filterInput(event: KeyboardEvent, regEx: RegExp){
    const restrict = !regEx.test(event.key) && event.key != "Backspace" && event.key !== "ArrowLeft" && event.key !== "ArrowRight" && event.key !== "Delete";
    if (restrict){
        event.preventDefault();
    }
}

My concerns are that the performance might be bad or is there any exceptions I might missing. Also I dont really like the idea of comparing with strings (Backspace, Delete, ArrowLeft and ArrowRight).

Is there any thinkable but also useful and better way to do this? or should I just stick to my function above.

Happy to hear your suggestions.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  • Don't use ev.keyCode

  • Don't use a blacklist filter (any value is allowed, except x, y, z...)


  • Do use ev.key

  • Do use a whitelist filter (the only values allowed are a, b, c...)


Suggestions:

  • Use a Set of valid ev.key values:

    if (!set.has(ev.key)) ev.preventDefault();
    
  • If you are concerned about string type validation for comparisons with ev.key, you can test values here and create a string enum or union of string literals for use in your program.

about 4 years ago · Juan Pablo Isaza Relatório
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