regular expression to check if zip code text is not from a particular state

So I want to write a validation that checks a zip code in a html input text. I want to check if a zip code is from a particular state then it will give an error, telling that it is from that state and it's not allowed.. otherwise if the user enters some other zipcode, this should be fine. How do I do that?

The way ZIP codes are assigned, each states' ZIP codes fall within a particular range. If you ignore the fact that not all ZIP codes in those ranges are currently in use, you could construct a regex that would match only ZIP codes for particular states. (see for the ranges).

I think a function with some if statements would be simpler though:

function isAllowedZIP(zip) {
     if (zip >= 10000 && zip < 15000) // New York
         return false;

     if (zip >= 7000 && zip < 9000) // New Jersey
         return false;

     if (zip >= 90000 && zip < 96200) // California
         return false;

     return true;

You are going to need to make an API call to something. An example would be Yahoo Geocoding API.

You will need to register your app in order to use the api

Once you've got your appid, you would use code like the following:

var validateZipcodeFromState = function (zipcode, state) {
  var data = { zip: zipcode, appid:  <YOUR APP ID };
  $.get("", data, function(result) {
    if(result.state != state){
      alert("invalid zip code");

Bind that function to a triggering event and you should be set.

Edit: This would have cross domain ajax problems. You would need to proxy the call or something of that nature.

I don't know about the ranges of zip codes from state to state, but since a zip code is a fairly simple, 5-digit string, you could structure your regex as below. In this case, I'm looking for any zip code that begins with 1 through 5 or ends with 6 or 7.

var pattern = /^[1-5]\d\d\d\d|\d\d\d\d[6-7]$/;

pattern.test('12345'); // returns true
pattern.test('54321'); // returns true
pattern.test('00000'); // returns false
pattern.test('00007'); // returns true

You would now just modify the pattern above to suit the particular range of zip codes you're after.