Skip to content

Instantly share code, notes, and snippets.

@nathanchere
Last active March 31, 2020 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanchere/ad76a371e87e1691358203b2d2740305 to your computer and use it in GitHub Desktop.
Save nathanchere/ad76a371e87e1691358203b2d2740305 to your computer and use it in GitHub Desktop.
EAN / UPC validation
public class UpcCode
{
public static bool IsValid(string code)
{
if (string.IsNullOrEmpty(code)) return false;
if (!code.All(char.IsDigit)) return false;
if (code.Length < 12 || code.Length > 13) return false;
var digits = code.Select(c => int.Parse(c.ToString())).Reverse().Skip(1).ToArray();
var checkBit = int.Parse(code.Last().ToString());
var evenIndexDigits = digits.Where((_, i) => i % 2 == 0).Sum();
var oddIndexDigits = digits.Where((_, i) => i % 2 != 0).Sum();
var parity = (evenIndexDigits * 3 + oddIndexDigits) % 10;
if (parity != 0) parity = 10 - parity;
return checkBit == parity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment