Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda