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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.ISBN ValidatorValidate ISBN-10 and ISBN-13 identifiers with checksum verification, hyphen-tolerant input, and conversion between the two forms.Luhn Checksum ValidatorValidate numeric identifiers with the Luhn algorithm and see the checksum sum and suggested final digit on failure.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.