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!
31797e86-4589-4798-9f99-833a7f4d6dce|1|5.0
Tags: