2

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.

3
  • 1
    there is a nice jQuery plugin for this: digitalbush.com/projects/masked-input-plugin Commented Jun 6, 2010 at 20:11
  • Don't forget to validate on the server side, too. It's very easy to stop JavaScript outputting 'irritating' messages like “Hey you! You're supposed to only input numbers here!”. Commented Jun 6, 2010 at 21:03
  • @meo, pretty nice indeed. Thanks. Commented Jun 6, 2010 at 22:28

1 Answer 1

6

You can always check with parseInt:

if (number == parseInt(number))
Sign up to request clarification or add additional context in comments.

3 Comments

OR'ing a value with 0 is faster: if (number == (number | 0)).
BEWARE: both answers above will return true for the strings '0x10' and '10.000000', '00000', '-0', and '+0'. Virtually always parseInt should be passed 10 as the second parameter to force it to use base 10 ie. parseInt(number,10). |0 is probably no faster if passed a string.
BEWARE: also the string '0e-400' returns true for both given solutions... and there are probably other corner cases (maybe near +/-MaxInt). Validating integers is hard in Javascript :)

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.