Multiway if

Situation: 

You have several tests that you want to apply in a row. All have to pass to proceed. Often used in validation, and with the flag pattern.

Actions: 

Chain together a sequence of else ifs.

Explanation: 

Say you are doing some validation. A value must pass three tests:

  • Not empty
  • Greater than or equal to zero
  • Less than or equal to 48

Assume the value to test is in the variable inputValue. You can use a multiway if like this:

if ( inputValue == "" ) {
  alert("Sorry, the input value cannot be empty.");
  return;
}
else if ( inputValue < 0 ) {
  alert("Sorry, the input value cannot be negative.");
  return;
}
else if ( inputValue > 48 ) {
  alert("Sorry, the input value cannot be more than 48.");
  return;
}

If inputValue fails any of the tests, an error message will show, and the function containing the code will exit. Only if all three tests are passed will the code proceed.

You can mix this with the flag pattern. For example:

dataOk = true;
if ( inputValue == "" ) {
  alert("Sorry, the input value cannot be empty.");
  dataOk = false;
}
else if ( inputValue < 0 ) {
  alert("Sorry, the input value cannot be negative.");
  dataOk = false;
}
else if ( inputValue > 48 ) {
  alert("Sorry, the input value cannot be more than 48.");
  dataOk = false;
}
if ( ! dataOk ) {
  return;
}

A variant uses a variable with an error message as a flag:

errorMessage = "";
if ( inputValue == "" ) {
  errorMessage = "Sorry, the input value cannot be empty.";
}
else if ( inputValue < 0 ) {
  errorMessage = "Sorry, the input value cannot be negative.";
  dataOk = false;
}
else if ( inputValue > 48 ) {
  errorMessage = "Sorry, the input value cannot be more than 48.";
}
if ( errorMessage != "") {
  alert(errorMessage);
  return;
}

This is more limited than the standard flag pattern, since it can only show one error message.