Regex to match only long integers in JS

Viewed 48

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} ...)?

3 Answers

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?!?

Not a pure regex solution, but in addition to validating the it "looks" like it's within range with regex, you can iterate over each index of the string and compare its value with the target string.

const MAX_VALUE = "9223372036854775807";
const lengthCheck = new RegExp(`^\\d{1,${MAX_VALUE.length}}$`);

function validateLongPositiveInteger(value) {
  if (!lengthCheck.test(value)) {
    return false;
  }

  if (value.length < MAX_VALUE.length) {
    return true;
  }

  for (let i = 0; i < MAX_VALUE.length; i++) {
    if (value[i] > MAX_VALUE[i]) {
      return false;
    }
    if (value[i] < MAX_VALUE[i]) {
      return true;
    }
  }
  return true;
}

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