Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
¿Cómo validar los valores de KeyboardEvent para una entrada de número?

Estoy teniendo una entrada de número de tipo. Los navegadores Chromium también parecen restringir la entrada, sin embargo, Firefox no lo hace y esto es un problema (para nuestros gerentes de producto). Así que descubrí, ¿por qué no filtrar mientras tengo una entrada a través de un evento como Keydown, Keyup o Keypress?

Primero hice esta función para filtrar mi entrada:

 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(); } }

Sin embargo, estoy pensando en generalizar esta función y convertirla en algo como esto

 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(); } }

Después de buscar y profundizar en él, se me ocurrió una función tan general:

 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(); } }

Mis preocupaciones son si el rendimiento puede ser malo o si hay alguna excepción que pueda faltar. Además, no me gusta mucho la idea de comparar con cadenas (Retroceso, Eliminar, ArrowLeft y ArrowRight).

¿Hay alguna manera imaginable pero también útil y mejor de hacer esto? o debería limitarme a mi función anterior.

Feliz de escuchar sus sugerencias.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  • No use ev.keyCode

  • No use un filtro de lista negra (se permite cualquier valor, excepto x , y , z ...)


  • ev.key ev.key

  • Utilice un filtro de lista blanca (los únicos valores permitidos son a , b , c ...)


Sugerencias:

  • Use un Set de valores ev.key válidos:

     if (!set.has(ev.key)) ev.preventDefault();
  • Si le preocupa la validación del tipo de cadena para las comparaciones con ev.key , puede probar los valores aquí y crear una enumeración de cadena o una unión de literales de cadena para usar en su programa.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!