Search code examples
javascriptprompt

Is there a way I can loop this prompt to repeat itself if a word or negative number are entered?


A prompt for entering a max number for a higher-lower game. I need the prompt to repeat itself if a positive number is not entered.

      var maxInput = prompt("Please choose the maximum number.");
        var numberRounded = Math.round(maxInput);
        let rules = document.getElementById("rules");
        if (numberRounded > 1) {
            message.innerHTML = (numberRounded + " is the max number!");
            rules.innerHTML = ("Guess a number between 1 and " + numberRounded + "!");
            } else if (isNaN(numberRounded)) {
            var numberRounded = prompt("Please choose a number.");
        } ```

Solution

  • You can use regular expression like so:

    var userInputString="";
    while(!userInputString.match(/^[1-9]+[0-9]*$/)) {
      userInputString=prompt("Enter a positive whole number");
    }
    var userInputPositiveWholeNumber=Number(userInputString);
    console.log(userInputPositiveWholeNumber);

    The loop will not exit until the user has inputted a positive whole number.

    This regex has a beginning - ^, and an end $, but not middle.

    The beginning, following the ^:
    [1-9] = a digit between 1 and 9 (so no leading zero(s)).
    + = at least one (of the preceding range).

    The end, preceding the $:
    [0-9] = any digit (between 0 and 9).
    * = a non-negative count of occurrences - none, once, ... infinity (of the preceding range).

    Note: There is a cut-off number where larger numbers will be of d.dddd+/-ed+ format and they will lose accuracy.


    Previous version:

    The first part, [1-9]+, makes sure input starts with a digit that is not zero and not a minus sign, and no other character but a digit between 1 and 9.
    The second part, [0-9]* allows for any (even zero) number of digits of any digit to follow the first.
    Once the loop exits, we just cast the string to a number.