Javascript Prompt Validation?

I want to prompt the user to enter a sport (baseball, football, soccer, or track). Let's say I enter "Golf". How do I get it to keep asking me to enter a sport until I enter one of the valid sports? The sport determines what field they play on. Below is my code.

var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase (); 

switch (sport) {
    case "baseball": 
        field = "Field 1";
        break;
    case "football": 
        field = "Field 2";
        break;
    case "soccer":
        field = "Field 3";
        break;
    case "track":
        field = "Field 4";
        break;
    default: alert("Please enter a valid sport");
}

Answers:

Answer
loop:
while(true){
    var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase(); 
    switch (sport) {
        case "baseball": 
            field = "Field 1";
            break loop;
        case "football": 
            field = "Field 2";
            break loop;
        case "soccer":
            field = "Field 3";
            break loop;
        case "track":
            field = "Field 4";
            break loop;
        default: alert("Please enter a valid sport");
    }
}

or

var field;
while(true){
    var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase();
    if(!sport || /^(baseball|football|soccer|track)$/.test(sport)){
        field = "Field " + ("baseball|football|soccer|track".split("|").indexOf(sport)+1);
        break;
    }else{
        alert("Please enter a valid sport");
    }
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.