Reputation: 3794
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.
Upvotes: 2
Views: 7778
Reputation: 3321
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;
Upvotes: 3
Reputation: 616
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()
Upvotes: 2