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?

Sled
  • 18,541
  • 27
  • 119
  • 168
akshay
  • 755
  • 5
  • 16
  • 22
  • Just noting that [*Number.isInteger*](http://ecma-international.org/ecma-262/6.0/index.html#sec-isinteger) was added in ECMA-262 ed 6 aka ECMAScript 2015. – RobG Mar 25 '17 at 12:56

7 Answers7

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
}
Brian Donovan
  • 8,274
  • 1
  • 26
  • 25
  • 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. – RobG Mar 25 '17 at 13:11
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;
}
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);
}
Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 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. – Brian Donovan Dec 28 '10 at 06:49
  • tell that to Gagnon ;) I am only the messenger here, but point taken - update on it's way – mplungjan Dec 28 '10 at 07:21
  • 1
    Updated, however it might be that leading and trailing whitespace are to be considered invalid in a validation for integers only – mplungjan Dec 28 '10 at 07:34
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
selfboot
  • 1,490
  • 18
  • 23
0
var num = document.getElementById("myField").value;
if(/^\d+$/.test(num)) {
    // is an int
}
karim79
  • 339,989
  • 67
  • 413
  • 406
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.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

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

function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}
Raghav
  • 8,772
  • 6
  • 82
  • 106
  • It gives back true for a string contains a space. You should trim input before call of the length : `... && input.trim().length > 0` – The Bitman May 18 '18 at 15:53