jQuery:验证美国邮政的正则表达式不起作用

jQuery: Regex to validate US postal doesn't work

使用下面的代码,似乎没有任何效果。当我在邮政编码字段中键入非数字值时没有警告消息。请帮我找出问题所在。

$("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]" />

您的正则表达式将只接受美国邮政编码的 5 位数字 我不知道其余的分组正则表达式:(?:[-\s]\d{4}),它与您的需要无关。 我为您更正了代码:

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;                        
    }    
});

这有效 - 我们需要超时

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