Kanapolis
Kanapolis

Reputation: 311

Validate user input string passed into Javascript prompt method

Homework help vampire alert. I'm trying to add a user input string validation function to the "Rock, paper, scissors" game on Codecademy. The text editor on the Codecademy site validates my code as correct, but I'm not getting the expected behavior, which is to return an alert if the user fails to enter either a "rock", "paper", or "scissors" string.

I've piped together the conditions in the if statement below:

var userChoice = prompt("Do you choose rock, paper or scissors?");

function validateUserChoice(userChoice) {
    if (userChoice !== "rock" || userChoice !== "paper" || userChoice !== "scissors") {
        alert("You can only select rock, paper or scissors!");
        return false;
    }
};

And here's the rest of the game. When the preceding function is invoked, it appears that the compare function below is bypassed and whatever string the user typed into the prompt is printed to the screen (see console.log("User Choice: " + userChoice); at the bottom). Otherwise, the game returns the expected behavior when the function above is commented out:

var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
};

var compare = function(userChoice, computerChoice) {
    if (userChoice === computerChoice) {
        return "The result is a tie!";
    };

    if (userChoice === "paper") {
        if (computerChoice === "rock") {
            return "paper wins";
        } else {
            if (computerChoice === "scissors") {
                return "scissors wins";
            }
        }   
    };

    if (userChoice === "scissors") {
        if (computerChoice === "rock") {
            return "rock wins";
        } else {
            if (computerChoice === "paper") {
                return "scissors wins";
            }
        }
    }
};
console.log("User Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
compare(userChoice, computerChoice);

Upvotes: 0

Views: 775

Answers (1)

jqheart
jqheart

Reputation: 767

Try changing the condition like below,

function validateUserChoice(userChoice) {
    if (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors") {
        alert("You can only select rock, paper or scissors!");
        return false;
    }
};

Upvotes: 3

Related Questions