JavaScript - Test for an integer

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)

UPDATE

I have fixed the code that had an error and added a var called key to store the key pressed code using keyCode and which, that depend of the browser.

var key = e.which || e.keyCode;

Thanks Donald.McLean :)


If you want to check if you are writing numbers while typing (and avoid writing other characters into your input field), you can use this simple function and you can define the elements allowed (this include whatever you want to filter). In this way you can choose not only integers but for example a certain group of characters. The example is based in jQuery to attach it to an input field.

$('#myInputField').keypress(function(e)
{
    var key = e.which || e.keyCode;

    if (!(key >= 48 && key <= 57) && // Interval of values (0-9)
         (key !== 8) &&              // Backspace
         (key !== 9) &&              // Horizontal tab
         (key !== 37) &&             // Percentage
         (key !== 39) &&             // Single quotes (')
         (key !== 46))               // Dot
    {
        e.preventDefault();
        return false;
    }
});

If you use other key than the defined, it won't appear into the field. And because Angular.js is getting strong these days. this is the directive you can create to do this in any field in your web app:

myApp.directive('integer', function()
{
    return function (scope, element, attrs)
    {
        element.bind('keydown', function(e)
        {
            var key = e.which || e.keyCode;

            if (!(key >= 48 && key <= 57) && // Interval (0-9)
                 (key !== 8) &&              // Backspace
                 (key !== 9) &&              // Horizontal tab
                 (key !== 37) &&             // Percentage
                 (key !== 39) &&             // Single quotes (')
                 (key !== 46))               // Dot
            {
                e.preventDefault();
                return false;
            }
        });
    }
});

But what happens if you want to use ng-repeat and you need to apply this directive only in a certain number of fields. Well, you can transform the upper directive into one prepared to admit a true or false value in order to be able to decide which field will be affected by it.

myApp.directive('rsInteger', function() {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            if (attrs.rsInteger === 'true') {
                element.bind('keydown', function(e)
                {
                    var key = e.which || e.keyCode;

                    if (!(key >= 48 && key <= 57) && // Interval (0-9)
                         (key !== 8) &&              // Backspace
                         (key !== 9) &&              // Horizontal tab
                         (key !== 37) &&             // Percentage
                         (key !== 39) &&             // Single quotes (')
                         (key !== 46))               // Dot
                    {
                        e.preventDefault();
                        return false;
                    }
                });
            }
        }
    }
});

To use this new directive you just need to do it in a input type text like this, for example:

<input type="text" rs-integer="true">

Hope it helps you.