Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Validate a barcode UPC-E, UPC-A, EAN, EAN-14, SSCC
// checksum calculation for GTIN-8, GTIN-12, GTIN-13, GTIN-14, and SSCC
// based on http://www.gs1.org/barcodes/support/check_digit_calculator
function isValidBarcode(barcode) {
// check length
if (barcode.length < 8 || barcode.length > 18 ||
(barcode.length != 8 && barcode.length != 13 &&
barcode.length != 14 && barcode.length != 18)) {
return false;
}
var lastDigit = Number(barcode.substring(barcode.length - 1));
var checkSum = 0;
if (isNaN(lastDigit)) { return false; } // not a valid upc/ean
var arr = barcode.substring(0,barcode.length - 1).split("").reverse();
var oddTotal = 0, evenTotal = 0;
for (var i=0; i<arr.length; i++) {
if (isNaN(arr[i])) { return false; } // can't be a valid upc/ean we're checking for
if (i % 2 == 0) { oddTotal += Number(arr[i]) * 3; }
else { evenTotal += Number(arr[i]); }
}
checkSum = 10 - ((evenTotal + oddTotal) % 10);
// true if they are equal
return checkSum == lastDigit;
}
@cebence

This comment has been minimized.

Copy link

cebence commented Dec 26, 2014

It fails when the check digit equals 10.
Line #24 should say:

checkSum = (10 - ((evenTotal + oddTotal) % 10)) % 10;
@tompazourek

This comment has been minimized.

Copy link

tompazourek commented Aug 7, 2015

The JS version does not have barcode.length != 12 at the beginning.

@spig

This comment has been minimized.

Copy link
Owner Author

spig commented May 14, 2016

@cebence @tompazourek - thank you for your fixes.

@alphanull

This comment has been minimized.

Copy link

alphanull commented Sep 23, 2016

Assuming I want to use this code (seems to work fine for me): What is the license type then? Would be nice if you could clarify this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.