By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,518 Members | 1,210 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,518 IT Pros & Developers. It's quick & easy.

How to add 19 more states to ip block.

P: 2
I'm using a web statistic service and I want to only allow certain states to my site as a testing mode for a certain period of time and block all non US countries.

I received the correct javascript below, but I can't figure out how to add the addtional states to the else statement. I tried everything. I don't know javascript. I need to add 19 more states to the else statement correctly. Can you give me the correct sequence to follow by adding 4 or five states as sampe to the else statement and letting me know how to end the statement correctly? The script below does work.

Expand|Select|Wrap|Line Numbers
  1. <script language="JavaScript">
  2. var geo = disp();
  3. if (geo[0] != 'US'){
  4.    alert('Sorry this site is only accessible from the USA');
  5.  
  6.    window.location = ('http://www.yahoo.com'); 
  7. }
  8. else {
  9.    if (geo[2] != 'CA' && geo[2] != 'TX' ){ (NEED TO ADD STATES HERE)
  10.       alert('Sorry this site is only accessible from California and Texas');
  11.  
  12.       window.location = ('http://www.yahoo.com'); 
  13.    }
  14. }
  15. </script>
Jan 11 '10 #1
Share this Question
Share on Google+
6 Replies


Dormilich
Expert Mod 5K+
P: 8,639
I recommend a switch statement
Expand|Select|Wrap|Line Numbers
  1. switch (geo[2])
  2. {
  3.     case: "CA":
  4.     case: "TX":
  5.     case: "WA":
  6.     // …
  7.     case: "TN":
  8.         // execute "valid" code
  9.         break;
  10.     default:
  11.         alert(…);
  12.         location.href = "…";
  13. }
Jan 11 '10 #2

P: 2
That was fast thanks.
Jan 11 '10 #3

Dormilich
Expert Mod 5K+
P: 8,639
you get 5 extra dice if you’re a moderator ;)
Jan 11 '10 #4

gits
Expert Mod 5K+
P: 5,390
another idea to shorten the code a bit would be to use a 'hash-map' like this:
Expand|Select|Wrap|Line Numbers
  1. var statesMap = { 'CA': 1, 'TX': 1, 'WA': 1, ... };
  2.  
  3. if ( geo[2] in statesMap) {
  4.     // valid handling
  5. } else {
  6.     // invalid handling
  7. }
  8.  
kind regards
Jan 11 '10 #5

Dormilich
Expert Mod 5K+
P: 8,639
and just another one using arrays:
Expand|Select|Wrap|Line Numbers
  1. var statesMap = ["WA", "TX", "CA", …];
  2. if (-1 == statesMap.indexOf(geo[2]))
  3. {
  4.     // invalid handling
  5. }
  6. else
  7. {
  8.     // valid handling
  9. }
even searching in a string were possible …

you see, there are many ways to do this
Jan 11 '10 #6

Plater
Expert 5K+
P: 7,872
Note: Poopy IE6 doesn't have the .indexOf() operator on its arrays.
Jan 11 '10 #7

Post your reply

Sign in to post your reply or Sign up for a free account.