7

How can i check is a text entered in a textbox is an integer or not? I used the NAN function but it accepts decimal values too.

How can I do this? Is there any built-in method?

1
  • Just noting that Number.isInteger was added in ECMA-262 ed 6 aka ECMAScript 2015. Commented Mar 25, 2017 at 12:56

7 Answers 7

17

Let's say the text field is referenced by the variable intfield, then you can check it like this:

var value = Number(intfield.value);
if (Math.floor(value) == value) {
  // value is an integer, do something based on that
} else {
  // value is not an integer, show some validation error
}
Sign up to request clarification or add additional context in comments.

1 Comment

This will treat empty strings, or those containing only whitespace, as valid integers. If intfield.value is "" (empty string), then Number("") returns 0 and Math.floor(value) == value returns true. It also returns true if value is left as an empty string.
1

Regular expressions would be a way:

var re = /^-?\d\d*$/
alert(re.test(strNumber)); // leading or trailing spaces are also invalid here

Complete example with updates:

http://rgagnon.com/jsdetails/js-0063.html

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
  var objRegExp  = /(^-?\d\d*$)/;  

  //check for integer characters
  return objRegExp.test(strValue);
}

Updated to handle whitespace - which possibly is not allowed in the validation but here it is anyway: Possible to continue to use the code from the link I gave (leftTrim/rightTrim) but here I reuse trim from .trim() in JavaScript not working in IE

function ignoreLeadingAndtrailingWhitespace( strValue ) {
  return strValue.length>0?validateInteger( strValue.trim() ):false;
}

if(typeof String.prototype.trim !== 'function') { 
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}


function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

3 Comments

You have an unnecessary capture group, which doesn't matter too much as you're just using test, but still is odd. Plus it doesn't account for whitespace on the beginning or end.
tell that to Gagnon ;) I am only the messenger here, but point taken - update on it's way
Updated, however it might be that leading and trailing whitespace are to be considered invalid in a validation for integers only
1
// validate if the input is numeric and between min and max digits
function validateNumberSize(inputtxt, min, max)
{
    var numbers = /^[0-9]+$/;
    if(inputtxt.match(numbers))
    {
        if(inputtxt.length >= min && inputtxt.length <= max)
        {
            return true;
        }
    }
    return false;
}

Comments

0
var num = document.getElementById("myField").value;
if(/^\d+$/.test(num)) {
    // is an int
}

4 Comments

You can't match a regular expression against a number.
Just got rid of the parseInt, realised that was wrong. Thanks Brian.
Negative integers not handled
@mplungjan - this is also true.
0

Form data is always text. My suggestion is that you parse it as integer and compare it with the original:

var sampleData = ["not a number", "0", "10", "3.14", "-12", "-0.34", "2e10", "34foo", "foo34"];
var integers = [], notIntegers = [];
for(var i=0, len=sampleData.length; i<len; i++){
    var original = sampleData[i];
    var parsed = parseInt(original, 10);
    if( !isNaN(parsed) && original==parsed ){
        integers.push(parsed);
    }else{
        notIntegers.push(original);
    }
}
alert("Integers: " + integers.join(", ") + "\nNot integers: " + notIntegers.join(", "));

This shows:

Integers: 0, 10, -12
Not integers: not a number, 3.14, -0.34, 2e10, 34foo, foo34

Scientific notation is not supported, neither thousand separators. If it's an issue, you need something different ;)

Update: I want to make clear that this is only one of the possible approaches, not the one and only Truth. This approach makes sense if you need to do math with the data so you have to get a numeric variable anyway.

2 Comments

I call overkill compared to /^-?\d\d*$/ and where is your function?
Of course, two lines is overkill compared to one line because it's exactly twice as code. Shame on me. (Do you really need help to encapsulate this into a function?)
0

If you are looking either for integer or decimal you can go for:

function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

1 Comment

It gives back true for a string contains a space. You should trim input before call of the length : ... && input.trim().length > 0
0

Best to use the regular expression as follows:

function isInteger(str) {
    var r = /^-?[0-9]*[1-9][0-9]*$/;
    return r.test(str);
}

Just a test demo:

> function isInteger(str) {
...     var r = /^-?[0-9]*[1-9][0-9]*$/;
...     return r.test(str);
... }
> isInteger("-123")
true
> isInteger("a123")
false
> isInteger("123.4")
false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.