Skip to content Skip to sidebar Skip to footer

Window.prompt Accept Only Numeric Values

I am trying (unsuccessfully although) to make a window.prompt which will accept only numeric values (0,1,2,3,...) but I believe that something I am doing wrong. Look at my function

Solution 1:

You should reduce your code to the minimum required to reproduce the issue, e.g.:

 var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10);

if (selection != (/^[0-9.,]+$/)){
  console.log('fail');
} else {
  console.log('pass');
}

This returns "fail" for any value because you're testing a number against a regular expression object, which can never be equal.

If you want the user to only enter digits, period (.) and comma (,), then leave the entered text as a string and test it using the test method. I've also inverted the test so it makes more sense:

var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10);

if ( /^[0-9.,]+$/.test(selection)) {
  console.log('pass');

} else {
  console.log('fail');
}

Solution 2:

You can use RegExp.test() to check your input like:

const isInteger = /^(\d)+$/g;
if(isInteger.test(selection)) {
  console.log('Correct input!');
  // ... code
}

Post a Comment for "Window.prompt Accept Only Numeric Values"