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

251
Visualizações
jQuery: Regex to validate US postal doesn't work

With the code below, nothing seems to work. No alert message when I type non-numeric values in the Zipcode field. Please help me identify the issue.

$("input:text[name='address_1[zip]']").keyup(function(e) {
  var charCode = (e.which) ? e.which : event.keyCode
  if (String.fromCharCode(charCode).match(/^\d{5}(?:[-\s]\d{4})?$/)) {
    console.log("Please enter a number for zip code");
    $("input[name='address_1[zip]']").val("");
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<input type="text" name="address_1[zip]" />

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

0

This works - we need the timeout

const re = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
$("input:text[name='address_1[zip]']").on("blur", function(e) { 
  const $this = $(this);
  if (this.value && !re.test(this.value)) setTimeout(function() { $this.val(""); $this.focus() },100);
});
.red { border: 1px solid red  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<input type="text" name="address_1[zip]" /><input type="text" name="city" />

about 4 years ago · Juan Pablo Isaza Relatório

0

Your regex is about to only accept 5 digits for US ZIP and i have no idea about the rest of grouping regex : (?:[-\s]\d{4}) , it is not related to what you need. and i corrected the code for you :

jQuery("input:text[name='address_1[zip]']").keyup(function(e) {
    //var charCode = (e.which) ? e.which : event.keyCode    
    // no needed!
    if (!$(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) {
        alert("Please enter a number for zip code");
        jQuery("input[name='address_1[zip]']").val("");
        return false;                        
    }    
});
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