JavaScript Determine Valid Integer

by aherrick 13. October 2009 05:02

I need a simple function to determine if a value was a valid integer.  Meaning that the value is a whole number (positive or negative) and doesn’t contain decimals. 

Below is what I came up with.

// check valid integer
function IsValidInt(s) {

    var valid = false;
    if (s != null && s != "" && !isNaN(s)) {
        valid = parseInt(s, 10) == s;
    }
    return valid;
}

Breaking it down we assume that the value is invalid.  We verify the value is not null, not an empty string, and use JavaScript’s built in NaN() (Not a Number) function to determine if it is a valid number.

Then use other JavaScript built in function, parseInt() and compare it to the original passed in value.  parseInt() will evaluate the value and return an Integer.  By comparing the returned integer and our passed in value, we can determine if the passed in value is valid.

I came up with this basic test suite function to show it validating.

function TestIsValidInt(){
    var results = ''
    results += (IsValidInt('-1')?"Pass":"Fail") + ": IsValidInt('-1') => true\n";
    results += (IsValidInt('-1.5')?"Pass":"Fail") + ": IsValidInt('-1.5') => false\n";
    results += (IsValidInt('0')?"Pass":"Fail") + ": IsValidInt('0') => true\n";
    results += (IsValidInt('asdf')?"Pass":"Fail") + ": IsValidInt('asdf') => false\n";

    alert(results);
}

Check out the example page to see it in action!

Enjoy!

Tags:

Comments

10/13/2009 11:18:41 AM #

Mr. Burns

i think your ideas are so cool im obsessed with ur website i check it everyday where do u live and do u like chickens?

Mr. Burns United States



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!


Categories

None

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008