Validating user inputs


#1

In my code I asked user to chose between like, love or hate. How can I ask the user to chose again if he doesnt chose between the 3. I want prompt the user for the option again and again until he chooses one of the three.


#2

I have a long solution. If anyone has a better solution then please share.

var user = prompt("Do you like, love or hate chocolate?").toLowerCase();

var i = 2;

var test = function () {
if(user === "like") {
i = 1;
}
else if (user === "love") {
i = 1;
}
else if (user === "hate") {
i = 1;
}
else {
user = prompt("Chose between like, love or hate");
}
};

while (i === 2) {
test ();
};


#3

Hi @aman31591gmail_com

Check this code if you like it

var user;
var response = true;
var getReplay = true;

while(getReplay){
    while(response){
        user = prompt("Do you like, love or hate chocolate?").toLowerCase();
        if(user === "like"){
            console.log("Ok you like it, good");
            response = false;
        }else if(user === "love"){
            console.log("waouw really ?");
            response = false;
        }else if(user === "hate"){
            console.log("Ok... Bye");
            response = false;
        };
    };
    
    if(confirm("Do you want to replay ?")){
        getReplay = true;
        response = true;
    }else{
        getReplay = false;
    };
};

Hold on :wink:


#4

If statements are useful for sure and in many occasions I would agree with you on this. But for this type of condition statement I would suggest instead of using If-else if statements, to rather use a "switch" condition statement like so.

while(getReplay){
    while(response){

        user = prompt("Do you like, love or hate chocolate?").toLowerCase();

        switch(user){
          case 'like':
            console.log("Ok you like it, good");
            response = false;
            break;
          case 'love':
            console.log("waouw really ?");
            response = false;
            break;
          case 'hate': 
            console.log("Ok... Bye");
            response = false;
            break;
          default:
            console.log("...What?");
            break;
       }
    };
    
    if(confirm("Do you want to replay ?")){
        getReplay = true;
        response = true;
    }else{
        getReplay = false;
    };
};

By no means are you wrong. This is simply a preference thing as it cleans the code up to look a little bit better.


#5

@lolman show you the level 2 : switch :smirk:
Of course it's more appropriate for your program, it's abundantly clear with a switch