Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!