tags:

views:

358

answers:

3

Hello,

I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already in place. However, I cannot seem to verify that the user enters an actual integer. I am currently trying the following code:

    function IsValidAge(value) {
        if (value.length == 0) {
            return false;
        }

        var intValue = parseInt(value);
        if (intValue == Number.NaN) {
            return false;
        }

        if (intValue <= 0)
        {
            return false;
        }
        return true;
    }

The odd thing is, I have entered individual characters into the textbox like "b" and this method returns true. How do I ensure that the user is only entering an integer?

Thank you

+13  A: 
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
   alert('I am an int');
   ...
}

That will absolutely, positively fail if the user enters anything other than an nonnegative integer.

karim79
This also fails if the user enters a negative integer.
Jason S
(of course, ages aren't negative, but you should be specific about whether you are testing for any integer or any nonnegative integer.)
Jason S
@Jason S - you're right, edited to reflect your comment.
karim79
A: 

use isNaN(n)

i.e.

if(isNaN(intValue))

in place of

if (intValue == Number.NaN)
Jumipo
+6  A: 

For real int checking, use this:

function isInt(value) { 
    return !isNaN(parseInt(value)) && (parseFloat(value) == parseInt(value)); 
}

The problem with many int checks is that they return 'false' for 1.0, which is a valid integer. This method checks to make sure that the value of float and int parsing are equal, so for #.00 it will return true.

Paul