tags:

views:

46

answers:

2

Hello,

I'm building a shopping cart and I would like to use a JavaScript function to validate user input when entering the quantity value in the quantity text input. I would like to allow the entering of integer values only (no floats, no other characters).

I know that I can apply this function using onKeyUp event and also I found isNaN() function, but it returns true even for floats (which is not ok).

Can you guys help me out with this one?

Thanks.

+2  A: 

You can always check with parseInt:

if (number == parseInt(number))
Victor Stanciu
OR'ing a value with 0 is faster: `if (number == (number | 0))`.
Marcel Korpel
A: 

Regex is one option

valid = /^\d+$/.test(someVarSupposedToBeInteger);

Negatives will not validate, but it sounds like they souldn't, either (shopping cart).

Lauri Lehtinen
"Regex is one option" ... but a bloody horrible one.
icio
Care to elaborate?
Lauri Lehtinen