Mod-97 Check Digit Calculation and Validation

Compute ISO 7064 mod-97 check digits and validate long number strings without exceeding JavaScript safe integer precision.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
export function mod97(input) {
  const digits = String(input).replace(/[\s-]/g, "");
  if (!/^\d+$/.test(digits)) throw new TypeError("input must contain digits only");
  let remainder = 0;
  for (const char of digits) {
    remainder = (remainder * 10 + Number(char)) % 97;
  }
  return remainder;
}

export function computeCheckDigits(base) {
  const digits = String(base).replace(/[\s-]/g, "");
  if (!/^\d+$/.test(digits)) throw new TypeError("base must contain digits only");
  const check = 98 - mod97(digits + "00");
  return String(check).padStart(2, "0");
}

export function validateCheckDigits(value) {
  const digits = String(value).replace(/[\s-]/g, "");
  if (!/^\d+$/.test(digits)) throw new TypeError("value must contain digits only");
  return mod97(digits) === 1;
}

How it works

Count the functions mod97, computeCheckDigits and validateCheckDigits as the entire surface area of Mod-97 Check Digit Calculation and Validation.

for (const char of digits) is the loop that carries the per-item work. Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

Applying it

The primary signature is export function mod97(input)

Import mod97 from the file and call it — the rest of the code is implementation detail.

Statements that matter

if (!/^\d+$/.test(digits)) throw new TypeError("input must contain digits only");
if (!/^\d+$/.test(digits)) throw new TypeError("value must contain digits only");
if (!/^\d+$/.test(digits)) throw new TypeError("base must contain digits only");

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code throws `TypeError`. Handle it at the call site or let it propagate deliberately.
Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `mod97`, `computeCheckDigits`, `validateCheckDigits` at load time.