Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regular Expression to match 5 or 9 digit zipcode

I have a similar issue as my recent post but with a zip code validator, I am trying to convert over to a javascript validation process. my script looks like so:

    var regPostalCode = new RegExp("\\d{5}(-\d{4})?");
    var postal_code = $("input[name='txtzipcode']").val();
    if (regPostalCode.test(postal_code) == false) {
        bValid = false;
        msg = msg + '<li>Invalid Zip Code.</li>';
    }

From my recent post, I learned of the escape character that I needed at the beginning.

Basically, this function is validating a zip code that says 22601 which is correct, but it shouldn't validate 22601-1. There should have to be 4 digits after the dash like 22601-9999. It's like the second part of the validation is always true. Again this expression has worked in the past for me. Am I missing something? Is another escape character needed?

like image 902
Billy Logan Avatar asked Sep 16 '09 21:09

Billy Logan


People also ask

How do you match in regex?

2.1 Matching a Single Character The fundamental building blocks of a regex are patterns that match a single character. Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" .

What is regular expression in JavaScript examples?

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern.


2 Answers

Change your regex to:

new RegExp("^\\d{5}(-\\d{4})?$")
like image 42
Philippe Leybaert Avatar answered Nov 07 '22 13:11

Philippe Leybaert


Add anchors: new RegExp("^\\d{5}(-\\d{4})?$"). This forces the regular expression engine to only accept a match, if it begins at the first character of the string (^) and ends at the end of the string ($) being matched.

Note, that there might be a typo in the regular expression you hav given in your question: the second \d is missing a backslash.

like image 145
Dirk Avatar answered Nov 07 '22 13:11

Dirk