Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;                        
    }    
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading