Skip to content Skip to sidebar Skip to footer

Javascript Prompt Validation For Integer Input

I found myself needing to create a function to validate the input of a JS prompt as an integer. It turns out there is a little subtlety involved as pressing cancel returns null. Wh

Solution 1:

I run your code above, i try to input nothing and press OK and its show alert like i cancel the prompt. I think you should check also whether user input something or nothing. Your code might be looks like this:

functiongetInteger(){
    while(true){   	  
        let input = prompt("Input number: ");
        
        if (input == null) {
            // user hit cancelalert("I'm out of here.")
            returntrue;
        } else{
        	  if (input.length<=0 || isNaN( input ) ) {
                // user pressed OK, but input invalid or does not input anythingalert("Invalid input.");
            } else {
                // user typed something valid and hit OKreturnparseInt(input);
            }
         }                    
        }                     
}

getInteger()

Solution 2:

Can't answer about this prompt function behavior, but your last code is equivalent to:

let input;
while (input = prompt("Input number: ")) {
  if (isNaN(input)) {
    alert("Invalid input.");
  } else {
    return parseInt(input);
  }
}

Still outside the prompt behavior stuff, if you expect an integer (i.e. only figures) in your input string, I would tend to test this with a regular expression like /^\d+$/, instead of isNaN (what if I input "1.25"? Result wouldn't be NaN, and it'd return 1, but it doesn't seem to be what you intend to achieve).

EDIT the code is not exactly equivalent, so let's make it so:

let input;
while (input = prompt("Input number: ")) {
  if (isNaN(input)) {
    alert("Invalid input.");
  } else {
    return parseInt(input);
  }
}
alert("I'm out of here.");
return;

Post a Comment for "Javascript Prompt Validation For Integer Input"