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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!