akshay
akshay

Reputation: 755

checking if value of a textfield is integer in javascript

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?

Upvotes: 7

Views: 35477

Answers (7)

selfboot
selfboot

Reputation: 1520

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

Upvotes: 0

user1477929
user1477929

Reputation:

// 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;
}

Upvotes: 1

Raghav
Raghav

Reputation: 9630

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

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

Upvotes: 0

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

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.

Upvotes: 0

mplungjan
mplungjan

Reputation: 178109

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);
}

Upvotes: 1

karim79
karim79

Reputation: 342655

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

Upvotes: 0

Brian Donovan
Brian Donovan

Reputation: 8400

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
}

Upvotes: 17

Related Questions