1

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.

4 Answers 4

4
​function isInt(myVal) {
    return /^[+-]?\d+$/.test(myVal);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can simply use !isNaN(+myVal) or !isNaN(parseInt(myVal, 10))

4 Comments

You can always use parseInt if you don't like using the unary + to convert it to a number :)
Also myVal == ~~myVal should work for integers up to 31 bits or so (maybe it's 32; I can't remember).
Depends on what the user needs. If being able to convert it to a number is enough then it is correct.
"Validate Int Value in JavaScript" the title of the question. There was nothing mentioned about conversion.
0

Here is a short and sweet way

function isInt(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

1 Comment

That will also accept hex numbers. Use parseInt(myVal, 10) instead. Oh, and since when are zero and negative numbers not numbers? :p
0

If you use the modulus operator on a non-integer number or string,

either a remainder or NaN is returned.

function isInt(i) {
   return i%1===0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.