1

How can I check if x is an integer in javascript?

  • 1 -> OK
  • 11 -> OK
  • 1.1 -> not OK (decimal place)
  • null -> not OK (null)
  • a -> not OK (letter)
  • 1e1 -> not OK (letter)
  • 1 1 -> not OK (sapce in any position (include front or end))

    var x = document.forms["myForm"]["numofquestions"].value;    
    
    if (x==null || x=="" || isNaN(x) || x<1 || x>500 || (x%1 != 0)) {
       alert("Please fill in number between 1 - 1000");
    }
    
Ram
  • 143,282
  • 16
  • 168
  • 197
william lau
  • 39
  • 4
  • 7

2 Answers2

0

You could convert your value to an integer and check if this number is equal to your value:

parseInt(n) === n;
yckart
  • 32,460
  • 9
  • 122
  • 129
  • @undefined No, why should it fail? A string gets converted to a number (or NaN), and if this doesn't match to the input-value it will be falsy and everything is ok... – yckart Jun 04 '14 at 02:21
  • I had removed my comment, but I repeat it, this won't work. `parseInt('1')` is not strictly equal to `'1'`. – Ram Jun 04 '14 at 02:24
  • @undefined: Which is OK, isn't it? `'1'` is not an integer, it's a string. – Felix Kling Jun 04 '14 at 02:50
  • @FelixKling Well, `x` in the question refers to a form input's value, which is a string. OP is validating user inputs. – Ram Jun 04 '14 at 03:02
0

to check you can use

n % 1 === 0
aljgom
  • 7,879
  • 3
  • 33
  • 28