How to validate GTIN barcodes (UPC, EAN, ISBN) in JavaScript
If you build product feeds for Google Shopping, bad barcodes are one of the most common reasons products get disapproved. Shopify's barcode field accepts anything, so real catalogues end up with SKUs, typos and placeholders like 0000000000000 sitting where a GTIN should be. Before a barcode goes into a feed, it should at least pass the GS1 check digit test. It takes about 20 lines of JavaScript.…
Validating GTIN barcodes, which include UPC, EAN, and ISBN codes, in JavaScript is crucial for ensuring product feeds are approved by platforms such as Google Shopping. The GS1 check digit test can be implemented in about 20 lines of JavaScript to verify the validity of a GTIN. A GTIN is a global barcode number used to identify products, with common formats being 8, 12, 13, and 14 digits.
The check digit, the final digit of the barcode, is calculated by multiplying alternating digits by 3 and 1 from right to left, summing these products, and finding the number that, when added to this total, results in a multiple of 10. This check digit must match the last digit of the barcode for it to be valid. The function checkDigit takes the body of the barcode (excluding the check digit) and applies the GS1 algorithm to calculate the expected check digit.
The function validateGtin then checks if the input consists solely of digits, if its length is one of the valid GTIN lengths (8, 12, 13, or 14), and if it doesn't consist of a repeating sequence of digits, which would indicate a placeholder. If the calculated check digit matches the barcode's last digit, the function returns true, indicating the barcode is valid.
If the barcode fails any of these checks, the function returns false along with a reason for the failure. It is important to note that a passing checksum does not guarantee that the barcode is registered to a specific product; it only means the barcode is well-formed. To ensure a valid GTIN is used, it should be assigned to the exact variant of a product and not reused across different variants.
Additionally, GTINs should not be used for unique products like handmade goods, and the field should remain empty for such items. Implementing such checks in a Shopify feed, as FeedShine does, ensures only valid GTINs are sent out, preventing disapprovals due to invalid barcodes.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.