0
  function myFunction(){
    var hours=prompt("Enter the numbers of hours:","Enter here");

    if (hours<0)
    {
        alert("Inputs are negative. Click button to try again.");
        return;
    }
    if (typeof(hours)!='number')
    {
        alert("Input not a number. Click ...");
        return;
    }
    
    ... more code } 

I'm new to JavaScript and trying to test around with windows prompt. How can I control the input so that when the user inputs a negative number or a letter, it gives a warning alert and does not continue the function. The negative seems to work but the inputs as letters gives me errors. If I try to input a, it gives the error but at the same time, when I put in say 10, it also gives me the same error. I'm writing it specifically with windows prompt. Thanks in advance!

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
CompJ
  • 1
  • 1
  • Please don't SHOUT with all caps. – Scott Marcus Oct 07 '20 at 16:32
  • 2
    Anything the user enters into a `prompt` will be treated as a `String`. You can convert that `String` into a number in several ways (doing a numeric comparison as you are doing is one of them), but for your use case, you're better off using a regular expression with [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). – Scott Marcus Oct 07 '20 at 16:34
  • This is not prompt question but rather how do you Parse and validate string to number. Look at the link with similar question and many answers. https://stackoverflow.com/questions/175739/built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number – Francois Taljaard Oct 08 '20 at 08:27

2 Answers2

0

Input always gives a string. You can use the build-in isNaN-function.

var hours=prompt("Enter the numbers of hours:","Enter here");

if (isNaN(hours))
{
  alert("Input not a number. Click ...");
  
}
Milanmeu
  • 1
  • 3
0

The value returned from prompt will be a string, so it must be converted to a number. You may use parseInt to convert the string into an integer. To check if the result is NaN, use isNaN like below.

function myFunction() {
  let hours = parseInt(prompt("Enter the numbers of hours:", "Enter here"));

  if (hours < 0) {
    alert("Inputs are negative. Click button to try again.");
    return;
  }

  if (isNaN(hours)) {
    alert("Input not a number. Click ...");
    return;
  }
}

myFunction();
Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33