Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate a UPC or EAN code?

I need a C# .NET function to evaluate whether a typed or scanned barcode is a valid Global Trade Item Number (UPC or EAN).

barcode check digit

The last digit of a bar code number is a computer Check Digit which makes sure the bar code is correctly composed. GTIN Check Digit Calculator

like image 769
Zack Peterson Avatar asked Apr 13 '12 15:04

Zack Peterson


People also ask

How do you know if it is EAN or UPC?

In the world of retail sales there are primarily two barcode formats used, UPC and EAN. The UPC format (as shown below) is 12 digits while the EAN is 13. These two formats are predominantly used in their own regions, the UPC is used only in the US and Canada, while the EAN is used everywhere else globally.

How can I check my UPC code?

The thickness of the lines and the spaces are what make each UPC unique. Once you find the barcode, you'll find the UPC. The UPC is the set of 12 numbers under the barcode. The item at hand can be identified by a barcode scanner using the 12 numbers.


1 Answers

public static bool IsValidGtin(string code) {     if (code != (new Regex("[^0-9]")).Replace(code, ""))     {         // is not numeric         return false;     }     // pad with zeros to lengthen to 14 digits     switch (code.Length)     {         case 8:             code = "000000" + code;             break;         case 12:             code = "00" + code;             break;         case 13:             code = "0" + code;             break;         case 14:             break;         default:             // wrong number of digits             return false;     }     // calculate check digit     int[] a = new int[13];     a[0] = int.Parse(code[0].ToString()) * 3;     a[1] = int.Parse(code[1].ToString());     a[2] = int.Parse(code[2].ToString()) * 3;     a[3] = int.Parse(code[3].ToString());     a[4] = int.Parse(code[4].ToString()) * 3;     a[5] = int.Parse(code[5].ToString());     a[6] = int.Parse(code[6].ToString()) * 3;     a[7] = int.Parse(code[7].ToString());     a[8] = int.Parse(code[8].ToString()) * 3;     a[9] = int.Parse(code[9].ToString());     a[10] = int.Parse(code[10].ToString()) * 3;     a[11] = int.Parse(code[11].ToString());     a[12] = int.Parse(code[12].ToString()) * 3;     int sum = a[0] + a[1] + a[2] + a[3] + a[4] + a[5] + a[6] + a[7] + a[8] + a[9] + a[10] + a[11] + a[12];     int check = (10 - (sum % 10)) % 10;     // evaluate check digit     int last = int.Parse(code[13].ToString());     return check == last; } 
like image 130
Zack Peterson Avatar answered Sep 21 '22 20:09

Zack Peterson