views:

119

answers:

3

Trying to do front-end validation on an html input instead of throwing an exception in the java back end.

+2  A: 

Check whether the number is more than 2147483647.

For example:

if (parseInt(num, 10) > 2147483647)
    //BAD!!!
SLaks
Good -- might be worth mentioning that you *must* do input validation on the Java back end as well as the front end.
Jonathon
@SLaks: Perhaps you need to check the lower bound (-2147483648) as well.
KennyTM
it is signed, so all of the above apply. why didn't I think of this?
+1  A: 
if ((the_number >> 0) != the_number) {
  // overflow...
}

You still need a server-side check because the client-side may turn off Javascript, etc.

KennyTM
@KennyTM - if someone has only worked with JavaScript and Java, they might not be familiar with lower level operations like bit shifts -- could you flesh out an explanation of what you're doing? OP doesn't know enough to work out what 32-bit overflow would look like, so an explanation would probably help.
Jonathon
I am familiar with 32-bit overflow. does javascript explicitly use 32-bit integers, or is this open to implementation?
@user: 11.7.2 The Signed Right Shift Operator: "The result is a signed 32-bit integer." (Ref: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
KennyTM
A: 

Just check:

if (parseInt(myNumberAsString, 10) > 2147483647) {  alert("Invalid int!"); }
Phill
Oops, too late!
Phill