JavaScript - Test for an integer

Viewed 90968

I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already in place. However, I cannot seem to verify that the user enters an actual integer. I am currently trying the following code:

    function IsValidAge(value) {
        if (value.length == 0) {
            return false;
        }

        var intValue = parseInt(value);
        if (intValue == Number.NaN) {
            return false;
        }

        if (intValue <= 0)
        {
            return false;
        }
        return true;
    }

The odd thing is, I have entered individual characters into the textbox like "b" and this method returns true. How do I ensure that the user is only entering an integer?

Thank you

11 Answers
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
   alert('I am an int');
   ...
}

That will absolutely, positively fail if the user enters anything other than an nonnegative integer.

For real int checking, use this:

function isInt(value) { 
    return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10)); 
}

The problem with many int checks is that they return 'false' for 1.0, which is a valid integer. This method checks to make sure that the value of float and int parsing are equal, so for #.00 it will return true.

UPDATE:

Two issues have been discussed in the comments I'll add to the answer for future readers:

  • First, when parsing string values that use a comma to indicate the decimal place, this method doesn't work. (Not surprising, how could it? Given "1,001" for example in the US it's an integer while in Germany it isn't.)
  • Second, the behavior of parseFloat and parseInt has changed in certain browsers since this answer was written and vary by browser. ParseInt is more aggressive and will discard letters appearing in a string. This is great for getting a number but not so good for validation.

My recommendation and practice to use a library like Globalize.js to parse numeric values for/from the UI rather than the browser implementation and to use the native calls only for known "programmatically" provided values, such as a string parsed from an XML document.

use isNaN(n)

i.e.

if(isNaN(intValue))

in place of

if (intValue == Number.NaN)

I did this to check for number and integer value

if(isNaN(field_value * 1) || (field_value % 1) != 0 ) not integer;
else integer;

Modular Divison

Example
1. 25.5 % 1 != 0 and ,
2. 25 % 1 == 0

And if(field_value * 1) NaN if string eg: 25,34 or abcd etc ... else integer or number

Related