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]" />
CodePudding user response:
Your regex is about to only accept 5 digits for US ZIP and i have no idea about the rest of grouping regex :
and i corrected the code for you :(?:[-\s]\d{4})
, it is not related to what you need.
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;
}
});