我需要一个C# .NET函数来评估键入或扫描的条形码是否为有效的Global Trade Item Number (UPC或EAN)。

条形码号码的最后一位是计算机校验位,它确保条形码的正确组成。GTIN Check Digit Calculator
发布于 2012-04-13 23:17:51
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;
}发布于 2013-03-11 01:53:29
GS1 US在PDF文档中发布了GTIN的校验位计算算法(删除了不断变化的链接)。
以下代码使用linq检查GTIN条形码的最后一位: GTIN-8、GTIN-12 (UPC)、GTIN-13 (EAN)和GTIN-14 (ITF-14)。
private static Regex _gtinRegex = new System.Text.RegularExpressions.Regex("^(\\d{8}|\\d{12,14})$");
public static bool IsValidGtin(string code)
{
if (!(_gtinRegex.IsMatch(code))) return false; // check if all digits and with 8, 12, 13 or 14 digits
code = code.PadLeft(14, '0'); // stuff zeros at start to garantee 14 digits
int[] mult = Enumerable.Range(0, 13).Select(i => ((int)(code[i] - '0')) * ((i % 2 == 0) ? 3 : 1)).ToArray(); // STEP 1: without check digit, "Multiply value of each position" by 3 or 1
int sum = mult.Sum(); // STEP 2: "Add results together to create sum"
return (10 - (sum % 10)) % 10 == int.Parse(code[13].ToString()); // STEP 3 Equivalent to "Subtract the sum from the nearest equal or higher multiple of ten = CHECK DIGIT"
}发布于 2018-08-16 20:10:25
我找到了这个Nuget包:https://www.nuget.org/packages/ProductCodeValidator/
github中的代码是:https://github.com/ThomasPe/ProductCodeValidator。
下面是它的使用方法:
using ProductCodeValidator;
bool IsValidEAN(string EAN)
{
return EanValidator.IsValidEan(testEan));
}https://stackoverflow.com/questions/10143547
复制相似问题