Home > Enterprise >  Regex to match only long integers in JS
Regex to match only long integers in JS

Time:09-14

I need to create a regex to validate long integer inputs and ensure they are long integer positive values. This means that the valid range should be between 0 and 9223372036854775807

There is a way to create the regex without the need to manually add all the valid digits through ranges (i.e \d{0,18} | [1-8]\d{0,18} | 9[0-1]\d{0,17} | 92[0-1]\d{0,16} ...)?

CodePudding user response:

As I said in the comment, what you have is (close to) the best way to do it just with regex. This is usually not handled just by regex. Here is the simplest way to do it:

function validateLongInt(str) {
  return str.match(/^\d $/) && BigInt(str) <= 9223372036854775807n;
}

console.log(validateLongInt("0"))  // truthy
console.log(validateLongInt("1"))  // truthy
console.log(validateLongInt("9223372036854775807"))  // truthy
console.log(validateLongInt("-1")) // falsy
console.log(validateLongInt("9223372036854775808"))  // falsy
console.log(validateLongInt("A"))  // falsy
console.log(validateLongInt(""))   // falsy

Note that you cannot do this comparison with regular JavaScript numbers (or at least, not naively), since you are interested in numbers that are outside the safe integer range:

const max = 9223372036854775807;
console.log(max   1 > max); // false?!?

CodePudding user response:

If the reg exp is not a hard requirement then there is another way fo doing the validation:

const isValidPositiveLongNumber = (input: string | number | undefined, maxValue = 9223372036854775807): boolean => {

  if (input === undefined || input === null) {
    return false;  
  }
  const parsed = parseInt(input);
  if (isNaN(parsed)) {
    return false;
  }

  return parsed >= 0 && parsed <= maxValue;
}

console.log(isValidPositiveLongNumber("-6789"));
console.log(isValidPositiveLongNumber("12423554"));
  • Related