Search code examples
javascriptprompt

How to detect a invalid prompt answer?


Example of what I am trying to achieve:

var p = prompt("What is your favorite number?", 1, 2, 3, 4);
if (p) {
  function checkForInvalid() {
    const invalid = "invalid"
  }
}
if (p === invalid) {
  alert("Sorry, I don't know that number");
}

or something similar. I am relatively new to javascript. Could I use a function to check if the number is not specified within the prompt? I am not trying to validate anything...


Solution

  • const validNumbers = [1,2,3,4];
    
    var p = prompt("What is your favorite number?", validNumbers[0]);
    
    if (validNumbers.indexOf(Number(p)) == -1) {
      alert("Sorry, I don't know that number");
    }