Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

regex - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...