0

Just need to check that data user input on prompt is a number in Javascript

  var userAge = prompt("Please enter your age", "");
    if (typeof userAge == 'number') {
      document.write("You are " + userAge + " years old.");
    } else {
      document.write('Please enter a valid number');
    }

When I type my age, 28, to test, I expect that "You are 28 years old." will be printed to the document. However, it prints the else part of the code: "Please enter a valid number."

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Jevon Cochran
  • 1,565
  • 2
  • 12
  • 23

3 Answers3

0

Value from prompt is a string. Use isNaN instead:

var userAge = prompt("Please enter your age", "");
if (isNaN(userAge)) {
  document.write('Please enter a valid number');
} else {
  document.write("You are " + userAge + " years old.");
}
Kosh
  • 16,966
  • 2
  • 19
  • 34
0

Any number or value enclosed by a single or double quote in JavaScript is treated as a string, for that reason, typeof userAge is equal to 'string'.

Use this code instead:

var userAge = prompt("Please enter your age", "");

if (/^\d+[.]?\d+$/.test(userAge)) {
  document.write("You are " + userAge + " years old.");

} else {
  document.write('Please enter a valid number');
}
Cocest
  • 147
  • 1
  • 2
  • 15
0

Just convert to a number with Number.parseInt(), then use Number.isNaN() like so:

var userAge = parseInt(prompt("Please enter your age"));
if (isNaN(userAge)) {
  document.write('Please enter a valid number');
} else {
  document.write("You are " + userAge + " years old.");
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • You don't need to use `parseInt` as `isNaN` does the type coercion. Also it's not very good to copy-paste other peoples' answers. – Kosh Jan 18 '19 at 01:23
  • I didn't mean to @KoshVery but our answers are the same because the solution was the same. Also I didn't copy your answer. – Jack Bashford Jan 18 '19 at 03:12