简体   繁体   中英

State validation in a JavaScript registration form

I could do this:

var statevalidation = document.registration.statetextbox;
var state = statevalidation.value;

if(state=="AL" || state=="al" state=="AK" || state=="ak" || ...)
{
    document.getElementById("statemsg").innerHTML=("Good to go.");
    statemsg.style.color="green";
}
else
{
    statemsg.innerHTML=("Invalid state.");
    statemsg.style.color="red";
}

However, that leaves me with a long and unsavory if statement. I was wondering if someone knows a "cleaner" way of making sure that users put in a correct state abbreviation?

Not exactly "cleaner", but how about something like...

var state = statevalidation.value.toUpperCase();
var states = ["AL", "AK", ...];
var found = false;
for (var i = 0; i < states.length; i++) {
  if (states[i] == state) {
    found = true;
    break;
  }
}
if (found) {
  ...
} else {
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM