Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › barcode validation

Build Reliable EAN-13 and UPC-A Check-Digit Validation in JavaScript

By Freedom251 Team · · 8 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

EAN-13 and UPC-A use the same modulo-10 check-digit method. Keep each scanned identifier as a string, validate its length and ASCII digits, calculate the check digit from the data digits using alternating weights of 3 and 1 from the right, and compare it with the final digit. The JavaScript implementation below handles both formats without losing leading zeroes.

EAN-13 and UPC-A: what you are validating

UPC-A is the 12-digit retail representation of a GTIN-12. EAN-13 is the 13-digit representation of a GTIN-13. In both cases, the final character is a check digit calculated from all preceding characters. The preceding characters are often called the data portion, or the body of the key.

As an Amazon Associate I earn from qualifying purchases.

The formats are related, but they are not interchangeable in an application. A UPC-A value has 11 data digits plus one check digit; an EAN-13 value has 12 data digits plus one check digit. A scanner may deliver either format as text, and your validator must apply the length rule that matches the format you expect.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Property UPC-A EAN-13
GS1 identifier type GTIN-12 GTIN-13
Total digits 12 13
Data digits used to calculate the final digit 11 12
Check-digit algorithm Modulo 10, alternating weights 3 and 1 from the right Modulo 10, alternating weights 3 and 1 from the right
Typical retail context North American 12-digit consumer-product numbers GTIN-13 retail numbers used in many markets
Input requirement Exactly 12 ASCII decimal digits Exactly 13 ASCII decimal digits

GS1 regional guidance describes UPC-A in the context of 12-digit retail numbers assigned for fixed-weight consumer products intended for sale in North America, while EAN-13 covers GTIN-13 retail uses. The checksum is not a regional variation: both use the same weighting rule.

#1 Best Overall
WoneNice USB Laser Barcode Scanner Wired Handheld Bar Code Scanner Reader Black
  • Plug and play, This laser handheld barcode scanner has simple installation with any USB port and Ideal for businesses, shops and warehouse operations. Its function is unbeatable and easy to use, design is stylish
  • Compatible with Windows, Mac, and Linux; works with Word, Excel, Novell, and all common software
  • Scanning Speed: 200 scans per second. Scanning angle: Inclination angle 55°, Elevation angle 65°. Operational Light Source:Visible Laser 650-670nm.
  • Decode Capability: Code11, Code39, Code93, Code32, Code128, Coda Bar, UPC-A, UPC-E, EAN-8, EAN-13, ISBN/ISSN, JAN.EAN/UPC Add-on2/5 MSI/Plessey, Telepen and China Postal Code,Interleaved 2 of 5, Industrial 2 of 5, Matrix 2 of 5, etc ; 300 configurable options for prefix, suffix and termination strings, support turn on/off the beep.
  • Color: Black. Dimensions: 3.6 x 2.6 x 6.1 inches. Type of Cable: 2M or 6ft straight cable. Shock: 1.5m drop on concrete surface. Regulatory Approvals: FCC CE.

How the GS1 check digit is calculated

Start with the rightmost digit of the data portion, not the complete number. Give that digit a weight of 3, move one position left and give the next digit a weight of 1, then continue alternating 3 and 1 until every data digit has a weight. Multiply each digit by its weight and add the products.

The check digit is the amount required to bring that sum to the next multiple of ten. The compact formula is:

(10 - (sum % 10)) % 10

The second modulo operation matters when the sum is already a multiple of ten: in that case the check digit must be 0, not 10.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Worked EAN-13 example

Use the 12-digit data portion 400638133393. Assign weights from the right edge:

  • 3 × 3 = 9
  • 9 × 1 = 9
  • 3 × 3 = 9
  • 3 × 1 = 3
  • 3 × 3 = 9
  • 8 × 1 = 8
  • 3 × 3 = 9
  • 6 × 1 = 6
  • 0 × 3 = 0
  • 0 × 1 = 0
  • 4 × 3 = 12
  • 0 × 1 = 0

The products total 89. The next multiple of ten is 90, so the check digit is 1. The arithmetic result is therefore 4006381333931. This demonstrates the GS1 calculation only; it does not establish that the number is allocated to a particular product.

Rank #2
Eyoyo EYH2 Handheld USB Wired 2D 1D Barcode Scanner for POS Mobile Payment | Automatic QR Code Scanner PDF417 Data Matrix, Long USB Cable, for Convenience Store, Supermarket, Warehouse
  • Continuous Usage All Day: The EY-H2 USB barcode scanner is designed to always be ready for the next scan, which significantly reduces downtime and repair costs; it shortens checkout lines, improves customer service, and boosts business productivity
  • Plug and Play: Eyoyo wired barcode scanner is connected via a USB cable, with no need to install any driver or software; It offers effortless connection and is compatible with Windows, Mac, Android, and Linux; Seamlessly works with Quickbook, Word, Excel, Novell, and all common software
  • Supports Multiple 1D/2D Barcodes: Eyoyo QR code scanner scan with most 1D 2D barcodes with ease; 1D Barcodes: EAN, UPC, Code 39, Code 93, Code 128, UCC/EAN 128, Codabar, Interleaved 2 of 5, ITF-6, ITF-14, ISBN, ISSN, MSI-Plessey, GS1 Databar, Code 11, Industrial 25, Matrix 2 of 5, etc. 2D Barcodes: QR, DataMatrix, PDF417, and so on
  • Supports Screen Scanning: The Eyoyo 2D scanner is capable of reading barcodes from smartphone screens, such as mobile coupons, digital wallets, and digital loyalty cards; Before scanning, simply turn your screen brightness to the maximum
  • Sturdy Anti-Shock and Durable Design: The Eyoyo 2D barcode scanner features an ergonomic design made of high-quality ABS, enabling it to withstand repeated drops from 5 ft/1.5 m high onto the concrete ground; The durable plastic material ensures a long service life

Why the identifier should stay a string

A barcode number is an identifier, not a quantity you add, divide or compare numerically. Strings preserve leading zeroes, which are significant. Converting 036000291452 to a number and back can produce 36000291452, a different 11-character value that fails a UPC-A length check.

JavaScript numbers also have a finite exact-integer range. The largest integer that can be represented without precision loss is Number.MAX_SAFE_INTEGER, equal to 253 − 1. GTIN-12 and GTIN-13 values are shorter than that bound, but using numbers still creates avoidable formatting and input-validation problems. A string-first design works for these identifiers and scales to longer keys without changing the data model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validate ASCII decimal characters explicitly. The regular expression /^[0-9]+$/ accepts only the characters 0 through 9; it does not silently accept spaces, punctuation or other Unicode digits.

JavaScript implementation

function isAsciiDigits(value) {
  return typeof value === "string" && /^[0-9]+$/.test(value);
}

function calculateGs1CheckDigit(dataDigits) {
  if (!isAsciiDigits(dataDigits)) {
    throw new TypeError("Expected a non-empty string of decimal digits.");
  }

  let sum = 0;
  let weight = 3; // rightmost data digit gets weight 3

  for (let i = dataDigits.length - 1; i >= 0; i--) {
    sum += Number(dataDigits[i]) * weight;
    weight = weight === 3 ? 1 : 3;
  }

  return String((10 - (sum % 10)) % 10);
}

function isValidUpcA(value) {
  return isValidGs1Key(value, 12);
}

function isValidEan13(value) {
  return isValidGs1Key(value, 13);
}

function isValidGs1Key(value, requiredLength) {
  if (
    typeof value !== "string" ||
    value.length !== requiredLength ||
    !isAsciiDigits(value)
  ) {
    return false;
  }

  const data = value.slice(0, -1);
  const suppliedCheckDigit = value.slice(-1);
  return calculateGs1CheckDigit(data) === suppliedCheckDigit;
}

console.log(calculateGs1CheckDigit("400638133393")); // "1"
console.log(isValidEan13("4006381333931")); // true
console.log(isValidUpcA("036000291452")); // true

What each function guarantees

isAsciiDigits rejects non-string values and any character outside the ASCII digit range. calculateGs1CheckDigit accepts the data portion only, starts at the rightmost character with weight 3, and returns a one-character string. Returning a string keeps the calculation API consistent with the input API.

isValidGs1Key enforces the complete key’s required length before slicing off the final character. It then recalculates the check digit and compares characters rather than converting the complete identifier to a number. The two format-specific functions simply supply 12 for UPC-A and 13 for EAN-13.

Rank #3
Sale
Tera Barcode Scanner Wireless 1D Laser Cordless Barcode Reader with Battery Level Indicator, Versatile 2 in 1 2.4Ghz Wireless and USB 2.0 Wired
  • Larger battery enables longer continuous usage and twice the stand-by time. With the unique battery indicator light showing the remaining battery level, no more Low Battery Anxiety.
  • The curved handle is extended and widened. With specially designed smooth and flat trigger for a better grip.
  • The orange anti shock silicone protective cover can prevent scratches and friction even when dropped from up to 6.56 feet. IP54 technology protects the wireless barcode scanner from dust.
  • Plug and play with the USB receiver or the USB cable, no driver installation needed. Easy and quick to set up. Wireless transmission distance reaches up to 328 ft. in barrier free environment.
  • Supports almost all 1D Barcodes: Febraban Bank Code, Codabar, Code 11, Code93, MSI, Code 128, EAN-128, Code 39, EAN-8, EAN-13, UPC-A, ISBN, Industrial 25, Interleaved 25, Standard 25, Matrix. Reads damaged, fuzzy, reflective and smudged barcodes.

Number() is used only on one character that has already passed the ASCII-digit test. The complete identifier is never converted, so there is no opportunity to lose a leading zero or exceed numeric precision.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to validate a scanned value step by step

  1. Decide the accepted format. Use the UPC-A validator when the field must contain exactly 12 digits, and the EAN-13 validator when it must contain exactly 13.
  2. Capture the scanner output as text. Configure the input element or application state so the value is not coerced to a number.
  3. Choose a whitespace policy. The implementation above rejects leading and trailing spaces, line breaks and tabs. That strict behavior is useful when a malformed transport value should be visible. If your scanner integration deliberately appends a line ending, remove that terminator at the input boundary, document the normalization, and then call the strict validator.
  4. Check length and characters. Reject the value if it is not a string of exactly the expected length containing only ASCII digits.
  5. Separate data from the supplied check digit. Pass every character except the last to calculateGs1CheckDigit.
  6. Compare the calculated and supplied digits. A match means the key passes the modulo-10 check-digit test.
  7. Apply any business validation separately. If the application needs to know whether the key is allocated, associated with a product, or permitted in a particular workflow, perform that check independently.

Testing the validator

Unit tests should cover both valid and invalid arithmetic as well as input handling. These examples exercise the important boundaries:

Input Expected result Reason
4006381333931 with EAN-13 true The calculated final digit is 1.
036000291452 with UPC-A true Leading zero is retained as text and the final digit matches.
4006381333930 with EAN-13 false The final digit does not match the data portion.
4006381333931 with UPC-A false It has 13 digits, so it is not a UPC-A input.
36000291452 with UPC-A false A leading zero was lost; the value is only 11 characters.
03600029145A with UPC-A false The final character is not an ASCII decimal digit.
036000291452 with UPC-A false Strict validation rejects surrounding whitespace.

For a broader test suite, generate a data string, calculate its check digit, append it, and assert that the corresponding validator returns true. Then alter one data character or the final digit and assert false. Include values beginning with one or more zeroes so a refactor cannot accidentally reintroduce numeric conversion.

What a passing check digit does—and does not—prove

A passing result means only that the supplied final digit is arithmetically consistent with the preceding digits under the GS1 modulo-10 rule. It is useful for catching many transcription and scan errors, and barcode readers commonly perform EAN/UPC check-digit verification automatically.

It does not prove any of the following:

  • GS1 allocation: the arithmetic does not show that GS1 issued or allocated the identifier.
  • Product identity: the digits do not contain enough information to tell your application which product they represent. A database or registry lookup is required for that meaning.
  • Current product status: a mathematically valid key may be discontinued, duplicated in a local dataset, or outside the products your system accepts.
  • Print or symbol quality: the check digit says nothing about quiet zones, contrast, bar and space dimensions, magnification, damage, or scanner readability.
  • Correct symbology: a digit string can pass the checksum while being printed in the wrong barcode symbol or with an unsuitable layout.

Use wording such as “passes the GTIN check-digit test” or “check-digit valid” in logs and user interfaces. Avoid calling the result authentic, official, assigned or product verified unless separate evidence supports that claim.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
NetumScan USB 1D Barcode Scanner, Handheld Wired CCD Barcode Reader (1)
  • CCD Image Scanning Technology - NetumScan 1D barcode reader is equiped with advanced CCD sensor, which can quick capture 1D codes from paper and screen, including CODE128, UPC/EAN Add on 2 or 5, that can read even deformed barcodes, i.e. smudged, damaged, fuzzy, reflective barcodes, etc. Reading faster and more accurate than laser scanner.
  • Sturdy Anti-shock and Durable Design - Ergonomic design with high-quality ABS making it can support withstand repeated drops from 2m high to the concrete ground, durable to use. Durable plastic material guarantees long service life.
  • Three scanning mode - Key trigger mode + Auto-induction mode + Continuous Mode. There is no need to pull the trigger in auto-sensing mode and continuous scanning. Sometimes the self-sensing scanning function is in the inactive stage, please contact us and be at your service at any time.
  • Supported 1D Bar Code - 1D Decode Capability: UPC-A, UPC-E, EAN-8, EAN-13, ISSN, ISBN, Code 128, GS1-128, Code39, Code93,Code32, Code11, UCC/EAN128, Interleaved 2 of 5, Industrial 2 of 5, Codabar(NW-7), MSI, Plessey, RSS, China Post, etc.
  • Widely Use Range - This NetumScan Handheld USB barcode scanner can be used in supermarkets, convenience stores, warehouse, library, bookstore, drugstore, retail shop for file management, inventory tracking and POS(point of sale), etc.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Format, scanner and application decisions

When the application receives both formats

Do not infer the format from a country prefix or from a database guess. Route by an explicit field, symbology metadata from the scanner, or exact length. If an interface accepts both, try the 12-digit UPC-A rule and the 13-digit EAN-13 rule only after confirming the input consists solely of ASCII digits. Report the accepted format with the result so downstream code does not have to guess.

When a scanner adds an Enter key

Many keyboard-emulating scanners send the digits followed by Enter or another terminator. Treat that as transport framing, not part of the identifier. Strip only the documented terminator before strict validation; do not call a broad whitespace-normalization function that could hide an unexpected internal character.

When users paste values

Pasted text can contain spaces, non-breaking spaces or line breaks. Decide whether the product requires exact input or offers a visible normalization step. If normalization is allowed, show the normalized value and validate the result, while retaining the original in diagnostics when auditability matters.

Production conformance and version context

GS1 General Specifications Release 24.0 was ratified in January 2024. GS1 Ireland identifies Release 26, ratified in January 2026, as a current release for conformance material. The weighting and check-digit rule implemented here is stable across those descriptions, but production systems should consult the current GS1 release for requirements beyond arithmetic, including symbol construction, application identifiers and sector-specific rules.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

MDN’s documentation for Number.MAX_SAFE_INTEGER, updated October 22, 2025, describes the 253 − 1 exact-integer limit. That limit is one reason to keep identifiers as strings even though these two GTIN lengths fit within it: string handling also preserves formatting and makes validation rules explicit.

Best Value
NetumScan Desktop Barcode Scanner, USB QR Code Reader | Hands-free omnidirectional scanning for 1D, 2D and QR codes in warehouse, supermarket, retail store, bookstore and POS use
  • 【Omnidirectional Automatic Barcode scanner】NetumScan Barcode Scanner can easily capture bar codes 1D, 2D/QR on labels, paper, and mobile phone or computer displays,Sensitive and accurately and you can easily scan damaged barcode, distortion barcode, colorful barcode and reflective barcode, etc special barcode. Perfect for retail and other high-volume scanning applications.
  • 【Automatic Smart Sensing Scanning】Specially equipped induction trigger, the desktop barcode scanner support auto-sensing scanning, barcode recognition more intelligent. When you not use the barcode scanner for a while, it will be into a sleeping mode. When handsfree barcode scanner in sleeping mode, it will automatically be activated once the item moving, and read the barcode under the window to upload to your device.
  • 【Non-slip Base and Anti-shock Design】Our Handsfree Omnidirectional Barcode Scanner can be directly placed on the desk, the anti-slip base makes it more stable, Built-in anti-vibration system can avoid damage while falling from the height of 4.92 feet. IP54 technology protects the wireless barcode scanner from dust.
  • 【Improve Your Efficiency】Compared with handheld barcode scanner, our handsfree barcode scanner is more free of your hands, no need to pick up the scanner when scanning, whether it is cashier scanning goods, or customer scanning digital barcode from smart phone. It can improve work efficiency and save time. Also it is so easy to use, no need extra training necessary for new staff.
  • 【Plug and Play, Easy to Use】No need to install any software or app, Our desktop barcode scanner is Plug and play. Easily connected with your laptop, PC, POS by USB Cable. Ideal work for Windows XP/7/8/10, Mac OS, Linux.(Note:NOT compatible with Square/Clover/Shopify.)

Troubleshooting incorrect results

The calculated digit is off by one position

Check the starting point. Weight 3 belongs to the rightmost data digit, immediately before the check digit. Starting at the left or including the supplied check digit changes the alternating pattern and produces a different result.

Every value with a leading zero fails

Look for an HTML input declared as numeric, a JSON schema that coerces numbers, or a database column stored as an integer. Use text input and a character type, then verify that the value arrives with its original length.

A valid-looking number is rejected

Log the value with delimiters around it, such as "[" + value + "]", to reveal spaces or line breaks. Also confirm that the validator matches the format: a 13-digit EAN-13 cannot be sent to the 12-digit UPC-A function.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The checksum passes but the product lookup fails

That is expected behavior. Check-digit validation is an arithmetic integrity check, not an allocation or catalog service. Perform the registry or internal product lookup as a separate operation and handle “unknown product” independently from “invalid check digit.”

Recommended result model

For maintainable applications, return structured status rather than a bare boolean at the integration boundary. Distinguish errors such as wrong_length, non_ascii_digit and check_digit_mismatch, while keeping the arithmetic function small and deterministic. A successful status should say “check_digit_valid,” not “authentic.” This lets user interfaces explain a malformed scan without implying that a mathematically valid number has been verified against a product database.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

barcode validationcheck digitEAN-13GTINJavaScriptUPC-A

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.