/** * Whether a GTIN is a real barcode number: 8, 12, 13 or 14 digits whose * last is the check digit of the others (GS1 mod 10). * * @param {string} value - What was typed. * @returns {boolean} True for a valid GTIN. */ export const isValidGtin = (value: string): boolean => { const digits = value.replace(/[\s-]/g, ''); if (!/^(\d{8}|\d{12}|\d{13}|\d{14})$/.test(digits)) { return false; } const body = digits.slice(0, -1).split('').reverse(); const sum = body.reduce( (total, digit, index) => total + Number(digit) * (index % 2 === 0 ? 3 : 1), 0 ); return (10 - (sum % 10)) % 10 === Number(digits[digits.length - 1]); };