Skip to content

Instantly share code, notes, and snippets.

@jrharshath
Created April 25, 2016 20:54
Show Gist options
  • Save jrharshath/fe3887acde7d64e3e0385506f4033ad3 to your computer and use it in GitHub Desktop.
Save jrharshath/fe3887acde7d64e3e0385506f4033ad3 to your computer and use it in GitHub Desktop.
Validate 64-bit integer (Int64) in Javascript
function validateInt46(value)
{
if (!/^[-]?\d+$/.test(value)) return false;
var isNegative = value[0]==='-';
if (value.length < 18 + (isNegative ? 1 : 0)) return true;
if (value.length > (isNegative ? 20 : 19)) return false;
if (isNegative) value = value.slice(1);
var part1 = parseInt(value.slice(0, 10));
var part2 = parseInt(value.slice(10));
return part1 <= 9223372036 && part2 <= (isNegative ? 854775808 : 854775807);
}
@Ampersandy-zz
Copy link

Ampersandy-zz commented Aug 22, 2016

This is incorrect, btw. Consider 9 000 000 000 999 999 999. Your part1 test should return true immediately if the value is less than your target prefix, and false if it's larger. You only want to check the suffix if the target prefix is equivalent to the max prefix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment