-2

When I declared an if statement to check if the user types in a number instead of a direct word or letter, it will say "Not a valid input, please enter your response as a number." But then once you click ok on the alert box when it says that message the message you typed in the prompt that was wrong or not a number will still get put in the object.

How can I make it so if you type something else but a number, it will keep on saying, "Not a valid input, please enter your response as a number" until you type in a number?

var storeUsersInfo = [];
var amountOfUsers = prompt("How many users do you want?");
amountOfUsers = parseInt(amountOfUsers);
function returnUserInput() {
    var askFirstName = prompt("What is your first name?");
    var askLastName = prompt("What is your last name" + " " +     titleCase(askFirstName) + "?");
    var askAge = prompt("How old are you" + " " + titleCase(askFirstName) +  " " + titleCase(askLastName) + "?");

if(!Number.isInteger(Number.parseInt(askAge))) {
    alert("Not a valid input, please enter your response as a number.");
};

    return {
        firstName: titleCase(askFirstName),
        lastName: titleCase(askLastName),
        age: askAge
    };
};
function titleCase(string) {
    return string.charAt(0).toUpperCase() + string.slice(1); 
};

for(var i = 0; i < amountOfUsers; i++) {
    storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);
Michael M
  • 1
  • 6
  • 1
    Use a while loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while Or perhaps a do .. while loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while – Hamms Apr 27 '16 at 21:40
  • Possible duplicate of [Getting a better understanding of callback functions in JavaScript](http://stackoverflow.com/questions/483073/getting-a-better-understanding-of-callback-functions-in-javascript) – Ryan Apr 27 '16 at 21:42

2 Answers2

0

Instead show an alert call again to your function recursively.

if(!Number.isInteger(Number.parseInt(askAge))) {
    returnUserInput()
};

It will prompt again and again until response is ok.

Prescol
  • 615
  • 5
  • 12
0

Put the prompt, check and alert in a loop:

function returnUserInput() {
    var askFirstName = prompt("What is your first name?");
    var askLastName = prompt("What is your last name" + " " +     titleCase(askFirstName) + "?");
    while (true) {
        var askAge = prompt("How old are you" + " " + titleCase(askFirstName) 
                            +  " " + titleCase(askLastName) + "?");
        if(Number.isInteger(Number.parseInt(askAge))) break; // OK, exit loop
        alert("Not a valid input, please enter your response as a number.");
    };
    return {
        firstName: titleCase(askFirstName),
        lastName: titleCase(askLastName),
        age: askAge
    };
};
trincot
  • 317,000
  • 35
  • 244
  • 286