Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 709
akshay Avatar asked Dec 28 '10 06:12

akshay


2 Answers

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
}
like image 78
Brian Donovan Avatar answered Sep 21 '22 04:09

Brian Donovan


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);
}
like image 22
mplungjan Avatar answered Sep 21 '22 04:09

mplungjan