简体   繁体   中英

How to make sure the user enters a valid number in Javascript?

I'm asking the user to enter a number, so how can I use a loop to make sure they enter a number? If they don't enter a number, I want to prompt the user again for a valid number. Then I would loop the prompt until a valid number is entered.

    var size = prompt('Enter a size');
    size = Number(size);
    console.log(size);

 do { var size = prompt('Enter a size'), isNumber = isNaN(size); !isNumber && console.log(size); } while (isNumber);

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
var size = "";
while (!isNumber(size))
    size = prompt('Enter a size');;

using: Javascript - validation, numbers only

function promptLoop() {
    var size = prompt('Enter a size');
    size = Number(size);
    if (isNaN(size)) {
        alert("Must input numbers"); // optional
        promptLoop();
    }
    else console.log(size);
}

Try this examples:

        var size = prompt('Enter a size');
        //Test if is integer positive value.
        var patron = /^[0-9]+$/;
        if (patron.test(size)){
            //is a valid.
        }

        //Test if is integer negative or positive .
        patron = /^[-]?[0-9]+$/;
         if (patron.test(size)){
            //is a valid.
        }

        //Test if is decimal.
        patron = /^[-]?[0-9]+[\.]?[0-9]+$/;
         if (patron.test(size)){
            //is a valid.
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM