Con el siguiente código, nada parece funcionar. No hay mensaje de alerta cuando escribo valores no numéricos en el campo Código postal. Por favor, ayúdame a identificar el problema.
$("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]" />Esto funciona, necesitamos el tiempo de espera
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" />Su expresión regular está a punto de aceptar solo 5 dígitos para el código postal de EE. UU . y no tengo idea sobre el resto de la expresión regular de agrupación: y te corregí el código:(?:[-\s]\d{4}) , no está relacionado con lo que necesita.
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; } });