Skip to content

bug: EAN-13 does not validate provided check digit #65

@productdevbook

Description

@productdevbook

Summary

When a 13-digit EAN-13 code is provided (with check digit), src/encoders/ean.ts does not validate that the check digit is correct. In contrast, src/encoders/upc.ts correctly validates UPC-A check digits.

Details

ean.ts (NO validation):

export function encodeEAN13(text: string) {
  const digits = text.replace(/\D/g, "").split("").map(Number);
  if (digits.length === 12) {
    digits.push(calculateCheckDigit(digits));
  } else if (digits.length !== 13) {
    throw new Error("EAN-13 requires 12 or 13 digits");
  }
  // No check digit validation for 13-digit input!
}

upc.ts (HAS validation):

export function encodeUPCA(text: string) {
  // ...
  } else if (digits.length === 12) {
    const expected = calculateCheckDigit(digits.slice(0, 11));
    if (digits[11] !== expected) {
      throw new InvalidInputError(
        `UPC-A check digit mismatch: expected ${expected}, got ${digits[11]}`
      );
    }
  }
}

The same issue exists in encodeEAN8() — no check digit validation for 8-digit input.

Impact

Invalid EAN-13/EAN-8 codes with wrong check digits are silently accepted and encoded, producing barcodes that will fail at point-of-sale verification.

Fix

Add check digit validation for 13-digit EAN-13 and 8-digit EAN-8 input, matching the pattern used in UPC-A. Also use InvalidInputError instead of plain Error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions