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

137
Vistas
Prevent user inputting characters not in regex

I have an input field called exampleInput. I want the user only can write these two:

var pattern = /[A-Za-z][0-9]{7}[A-Za-z0-9]/;
var pattern2 = /^[XYZ][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/i;

If they try to write a number or a string which does not match the patterns, stop the character from being shown. How can Ido that?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to break it down into multiple patterns and check all possible states. Your first pattern has no start or end, not sure if that's what you want? In my example I'll go with pattern = /^[A-Za-z][0-9]{7}[A-Za-z0-9]$/ We can check for first letter and numbers in p0 = /^[A-Za-z][0-9]{0,7}$/ And then we have it all set, if value does not follow p0 nor pattern, block it. You can surely do more advanced regex but readability drops fast.

    document.getElementById('exampleInput').addEventListener('keydown', (e) => {
        if (["Backspace","Delete","Enter","ArrowLeft","ArrowRight"].indexOf(e.key) >= 0) { return; }
        var value = e.target.value.substring(0, e.target.selectionStart) + e.key + e.target.value.substring(e.target.selectionEnd);
        var pattern = /^[A-Za-z][0-9]{7}[A-Za-z0-9]$/;
        var p0 = /^[A-Za-z][0-9]{0,7}$/
        if (!p0.test(value) && !pattern.test(value)) {
            e.preventDefault();
        }
    })
<input id="exampleInput">

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