April 9, 2012
Validate Int Value in JavaScript
Question by user70192
I am trying to figure out how to ensure that a user enters an int into a text field with JavaScript. Currently, I have the following:
var myVal = $("#myField").val();
if (isInt(myVal)) {
alert("Awesome!");
} else {
alert("No Good");
}
function isInt(i) {
if ((i != null) && (i != undefined) && (i.length > 0)) {
alert(typeof i);
return (typeof i == 'number' && /^-?d+$/.test(i + ''));
}
return false;
}
If I enter 123 into the text field, I have noticed that the typeof i
is “string”. I’m not sure how to perform this kind of validation. Can someone please let me know? I was suprised I didn’t have any success when I Googled this.
Answer by Engineer
function isInt(myVal) {
return /^[+-]?d+$/.test(myVal);
}
Answer by Starx
Here is a short and sweet way
function isInt(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}