2

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.

What I originally tried (ported from a Python program) was:

function getInteger() {
    let number = null
    while ( number == null ) {
        let value = prompt( "Guess number: " )
        if ( isNaN( value ) ) {
            alert( "Invalid input." )
        } else {
            number = parseInt( value )
        }
    }
    return number;
}

However, this returns NaN if I cancel the prompt, which doesn't make sense as a return value (it seems isNaN(null)returns false). (By doesn't make sense, I mean "can't be meaningfully used by the rest of the program as it's not descriptive of what happened").

So after some thought, I came up with:

function getInteger(){
    while(true){
        let input = prompt("Input number: ");
        if (input && isNaN( input ) ) {
            // user pressed OK, but input invalid
            alert("Invalid input.");
        } else if (input) {
            // user typed something valid and hit OK
            return parseInt(input);
        } else {
            // User pressed cancel
            alert("I'm out of here.")
            return;
        }
    }
}

getInteger()

I'm curious as to whether I've covered all possible inputs? Also, whether my code is "well written" - is there a better way to do it? Is using while(true) considered a bad idea?

I'm aware that prompts in general are probably a bad idea, but that's not the point here.

Any help appreciated.

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure your code is equivalent. It doesn't handle the user clicking cancel which returns null. isNan(null) returns false.
Oh indeed, it does not alert("I'm outta here");, the falsy case is handled directly by the while (if input is falsy, then the while breaks).
2

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:

function getInteger(){
    while(true){   	  
        let input = prompt("Input number: ");
        
        if (input == null) {
            // user hit cancel
        		alert("I'm out of here.")
            return true;
        } else{
        	  if (input.length<=0 || isNaN( input ) ) {
                // user pressed OK, but input invalid or does not input anything
                alert("Invalid input.");
            } else {
                // user typed something valid and hit OK
                return parseInt(input);
            }
         }                    
        }                     
}

getInteger()

2 Comments

That's a good point.I think changing my first condition to if (input == "" || isNaN( input ) ) { also fixes it. The function seems surprisingly complex for something so simple though.
That wouldn't have happened using a regular expression instead of isNaN... just sayin'! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.