Drill

ProblemsJavaScript › validation

Verify a barcode

mediumvalidationJavaScript

A scanner sometimes misreads a digit. The EAN-13 check digit catches most of those before the wrong product reaches the basket.

barcodeValid(code: string) → bool

Solve it in the editor →

Where you start

function barcodeValid(code) {
  
}

Worked examples

CallResult
barcodeValid("4006381333931")true
barcodeValid("4006381333932")false
barcodeValid("400638133393")false
barcodeValid("400638133393a")false

Hint

The check digit is the thirteenth and takes part in the sum like any other.

Reference solution in JavaScript
function barcodeValid(code) {
  if (code.length !== 13) return false;
  let sum = 0;
  for (let i = 0; i < 13; i++) {
    const c = code[i];
    if (c < '0' || c > '9') return false;
    const d = code.charCodeAt(i) - 48;
    sum += i % 2 === 0 ? d : d * 3;
  }
  return sum % 10 === 0;
}

The same problem in another language

More validation problems in JavaScript