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

143
Visualizações
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 Respostas
Responde à pergunta

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 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