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

A regex to allow exactly 5 digit number with one optional white space before and after the number?

With the regex in the jQuery code below, I can restrict the input text field to accept only 5 digits but it allows more white spaces before and after the number than just one. I mean to match a 5-digit number that is at the beginning of the string or is preceded by at most one space and is at the end of the string or is followed by at most one space. Please help me refine my regex to meet my requirement.

jQuery("input:text[name='address_1[zip]']").change(function(e) {
if (!jQuery(this).val().match(/\b\d{5}\b/g)) { 
        alert("Please enter a valid zip code");
        jQuery("input[name='address_1[zip]']").val("");
        return false;                        
    }        
});

>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

I might suggest just using lookarounds here:

/(?<![ ]{2})\b\d{5}\b(?![ ]{2})/

This pattern says to:

(?<![ ]{2})  assert that 2 (or more) spaces do NOT precede the ZIP code
\b\d{5}\b    match a 5 digit ZIP code
(?![ ]{2})   assert that 2 (or more) spaces do not follow

Here is a demo showing that the pattern works.

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