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

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

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 Denunciar

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