validation.gtin
Check an EAN-8, UPC-A, EAN-13 or GTIN-14 barcode number against the GS1 mod-10 check digit.
1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra
Pinned by 17 tests, run in TypeScript, Python and Rust.
What it does
Checks a Global Trade Item Number - the number under a retail barcode - in any of its four lengths: EAN-8 (8 digits), UPC-A (12), EAN-13 (13) and GTIN-14 (14, used on cases and pallets). All four share one GS1 check digit: weight the digits 3, 1, 3, 1 ... starting from the digit just left of the check digit and moving left, sum, and the check digit is whatever brings the sum up to a multiple of ten.
Weighting from the right is the detail home-grown validators get wrong. EAN-13 weights its first digit 1, but EAN-8 and UPC-A weight their first digit 3, so code that always starts at the left with 1 accepts only EAN-13 and GTIN-14.
For example
validate_gtin(4006381333931)→ valid true, normalised 4006381333931, kind ean-13, gtin14 04006381333931, reason — an EAN-13, the standard retail barcodevalidate_gtin(036000291452)→ valid true, normalised 036000291452, kind upc-a, gtin14 00036000291452, reason — a UPC-A: its first digit is weighted 3, not 1validate_gtin(96385074)→ valid true, normalised 96385074, kind ean-8, gtin14 00000096385074, reason — an EAN-8, the other length a left-weighted check gets wrong
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
def validate_gtin(value: str) -> GtinCheck
| value | string | 8, 12, 13 or 14 digits, optionally grouped with spaces or hyphens |
| returns | GtinCheck |
The type it declares, generated into your project
@dataclass(frozen=True)
class GtinCheck:
"""The result of checking a GTIN. Every string is null when valid is false; reason is null when it is true."""
valid: bool
#: the digits only, at the length given
normalised: Optional[str]
#: ean-8, upc-a, ean-13 or gtin-14, from the length
kind: Optional[str]
#: left-padded with zeros to 14 digits, the form to compare and store
gtin14: Optional[str]
#: empty, bad-character, bad-length, all-zero or bad-check-digit
reason: Optional[str]
Your code names it in one line, in the file that uses it
from fune.validation.gtin import validate_gtin # validation.gtin@^1
from typing import List
from .validation_gtin_types import GtinCheck
#: The four GTIN lengths, and what each is called.
_KINDS = {8: "ean-8", 12: "upc-a", 13: "ean-13", 14: "gtin-14"}
def _invalid(reason: str) -> GtinCheck:
return GtinCheck(valid=False, normalised=None, kind=None, gtin14=None, reason=reason)
def validate_gtin(value: str) -> GtinCheck:
"""Check an EAN-8, UPC-A, EAN-13 or GTIN-14 against the GS1 mod-10 check digit.
A pass means the number was typed correctly, not that GS1 issued it.
Validators answer rather than raise: a malformed value is the answer "no".
"""
if not isinstance(value, str):
return _invalid("empty")
# Barcodes are printed in groups, so spaces and hyphens are ignored anywhere.
chars: List[str] = [ch for ch in value if ch != " " and ch != "-"]
if not chars:
return _invalid("empty")
# Compare against ASCII explicitly: str.isdigit() accepts Arabic-Indic and
# superscript digits, which the other two languages would reject.
if any(ch < "0" or ch > "9" for ch in chars):
return _invalid("bad-character")
digits = "".join(chars)
kind = _KINDS.get(len(digits))
if kind is None:
return _invalid("bad-length")
# Zero everywhere satisfies the arithmetic and has never been allocated.
if all(ch == "0" for ch in digits):
return _invalid("all-zero")
# Weights run 3, 1, 3, 1 ... leftwards from the digit next to the check
# digit. Counting from the right is what makes one rule serve all four
# lengths: EAN-13's first digit gets 1, EAN-8's and UPC-A's get 3.
total = 0
weight = 3
for ch in reversed(digits[:-1]):
total += (ord(ch) - 48) * weight
weight = 1 if weight == 3 else 3
check = (10 - total % 10) % 10
if check != ord(digits[-1]) - 48:
return _invalid("bad-check-digit")
return GtinCheck(valid=True, normalised=digits, kind=kind, gtin14=digits.rjust(14, "0"), reason=None)Install
fune build
With that line in your source, in a Python project (language python in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add validation.gtin
The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./validation.gtin-1.0.0-python.fune, or fetch it from a terminal with fune pull validation.gtin@1.0.0:python.
The whole function, every language, is one file too: validation.gtin-1.0.0.fune, 15,535 bytes, sha256 271a98258ce51ebf169572a6716b94b7754f5f7ba5b92aea276225a52ddf264d. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
# fune: before validation.gtin
after — your function gets the result and the arguments, and returns the final result.
# fune: after validation.gtin
replace — it requires no other capability, so there is no dependency to replace.
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show validation.gtin --steps.
# fune: step validation.gtin after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| an EAN-13, the standard retail barcode | 4006381333931 | → | valid true, normalised 4006381333931, kind ean-13, gtin14 04006381333931, reason — |
| a UPC-A: its first digit is weighted 3, not 1 | 036000291452 | → | valid true, normalised 036000291452, kind upc-a, gtin14 00036000291452, reason — |
| an EAN-8, the other length a left-weighted check gets wrong | 96385074 | → | valid true, normalised 96385074, kind ean-8, gtin14 00000096385074, reason — |
| a GTIN-14 case code built from the UPC-A with indicator 1 | 10036000291459 | → | valid true, normalised 10036000291459, kind gtin-14, gtin14 10036000291459, reason — |
| the UPC-A padded to GTIN-14 is the same number | 00036000291452 | → | valid true, normalised 00036000291452, kind gtin-14, gtin14 00036000291452, reason — |
| a Bookland EAN-13, which is an ISBN | 9780306406157 | → | valid true, normalised 9780306406157, kind ean-13, gtin14 09780306406157, reason — |
| printed groups with spaces and hyphens | 4 006381-333931 | → | valid true, normalised 4006381333931, kind ean-13, gtin14 04006381333931, reason — |
| last digit off by one | 4006381333932 | → | valid false, normalised —, kind —, gtin14 —, reason bad-check-digit |
| two adjacent digits transposed: a plain digit sum would miss it | 4006383133931 | → | valid false, normalised —, kind —, gtin14 —, reason bad-check-digit |
| eleven digits is no GTIN length | 03600029145 | → | valid false, normalised —, kind —, gtin14 —, reason bad-length |
Show the other 7 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| fifteen digits is too long | 100360002914590 | → | valid false, normalised —, kind —, gtin14 —, reason bad-length |
| a letter is a bad character, reported before the length | 40063813339A | → | valid false, normalised —, kind —, gtin14 —, reason bad-character |
| a dot is not an accepted separator | 4006381.333931 | → | valid false, normalised —, kind —, gtin14 —, reason bad-character |
| all zeros satisfies the arithmetic but is refused | 00000000 | → | valid false, normalised —, kind —, gtin14 —, reason all-zero |
| the empty string | → | valid false, normalised —, kind —, gtin14 —, reason empty | |
| separators only is empty | - | → | valid false, normalised —, kind —, gtin14 —, reason empty |
| a non-string is empty, not an exception | — | → | valid false, normalised —, kind —, gtin14 —, reason empty |
More from the author
A PASSING NUMBER IS WELL FORMED, NOT ALLOCATED. The check catches every single mistyped digit and most adjacent transpositions. It cannot say whether GS1 has issued the number or what product it is on; only GS1's registry (Verified by GS1) can.
RESULT: `valid`, then on success the digits (`normalised`), the `kind` implied by the length, and `gtin14`, the number left-padded with zeros to 14 digits. GS1 defines every GTIN as a 14-digit number with leading zeros, so `gtin14` is the form to store and compare: the UPC-A 036000291452 and the EAN-13 0036000291452 are the same item. `kind` is read from the length as given; an EAN-13 beginning with 0 is not re-labelled as a UPC-A.
ACCEPTED INPUT: ASCII digits, with ASCII spaces and hyphens ignored anywhere, because barcodes are printed in groups ("5 012345 678900"). Anything else makes the value invalid.
| reason | meaning | |-------------------|----------------------------------------------------------| | `empty` | nothing but spaces and hyphens, or not a string at all | | `bad-character` | something other than a digit, space or hyphen | | `bad-length` | not 8, 12, 13 or 14 digits | | `all-zero` | every digit is 0: satisfies the arithmetic, never issued | | `bad-check-digit` | the last digit does not match |
The checks run in that order and the first failure is the reason. Validators answer rather than throw.
Out of scope: GS1 prefix meaning (country of the member organisation, 978/979 Bookland, 02/20-29 restricted in-store numbers), GTIN-12 zero-suppressed UPC-E, and add-on codes. For ISBNs use validation.isbn, which also checks the prefix.
Source: GS1 General Specifications, section 7.9 "Check digit calculation" (https://www.gs1.org/services/how-calculate-check-digit-manually).
Files
| Path | Bytes |
|---|---|
| README.md | 2,570 |
| impl/python.py | 1,991 |
| impl/rust.rs | 2,757 |
| impl/typescript.ts | 1,943 |
| vectors.json | 3,292 |