Zip code validation for certain zip codes

Hi,

I’m trying to validate just zip code in the surrounding area. Right now, it will validate any zip code that starts with “8”. I only wanted to validate the zip codes for 87109, 87110, 87111, 87112, 87113, 87114 and anything else will be invalid. Any help will be appreciated and thank you.

`// zip code
s = $('input[name=home_zip]').val().replace(/\s+/g, '');
if ((s.length != 5)|(s.charAt(0) != '8')) {
add_error("#home_zip", "error_home_zip");
}

<div id="home_zip" class="inline" style="display: none;"> <span id="msg_zip">Zip Code</span> <input type="text" name="home_zip"></input> </div>

Here is my bit to help you out with the resolution. Try to use regular expression to validate zip code, it is much easier then other possible approaches.

You may find this link useful http://stackoverflow.com/questions/29204384/need-javascript-regex-to-check-string-starts-with-u-or-c-and-with-length-of-10

Here is Regex can be used for your need.

/^(8)$/

You can always validate this regex on online playgrounds for testing regular expressions like http://rubular.com or http://www.regexr.com/ or https://regex101.com/

Here’s what you currently have:

if ((s.length != 5)|(s.charAt(0) != '8')) {
    add_error("#home_zip", "error_home_zip");
}

It will be an error if the zip code is less than 87109 or greater than 87114, which we can translate directly in to code.

Replace the above code with the following:

if ((s.length !== 5 || s < 87109 || s > 87114) {
    add_error("#home_zip", "error_home_zip");
}

I’m using numbers there for the comparison instead of strings, so that the string itself will convert to a number, allowing for the easy range-check that you require.

Thank you for your help Lokesh and Paul! I’m a noob to this JavaScript. One more question, if I add a zip code that is not in the range of what I have, will I need to add the “else if” expression, or do I just continue to add it to the if with logical operator, ||? Thanks again.

    // zip code
    s = $('input[name=home_zip]').val().replace(/\s+/g, '');
    if ((s.length != 5)|(s < 87101 || s > 87125)) {
    } else if (s===87008) {
    } else if (s===87022) {
    add_error("#home_zip", "error_home_zip");
    }

That is a different set of conditions than you started with, and so a different type of solution will be required.

The general solution is to have an isValid variable that starts off false, and use a series of conditions to check for different criteria and set isValid to be true if that’s the case.

After all those checks you apply your error stuff if isValid is still false.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.