Last active
March 31, 2020 06:31
-
-
Save nathanchere/ad76a371e87e1691358203b2d2740305 to your computer and use it in GitHub Desktop.
EAN / UPC validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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