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?
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
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With