Skip to content

Instantly share code, notes, and snippets.

@lsancho
Created October 23, 2015 13:15
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 lsancho/7b21922547dbe867c357 to your computer and use it in GitHub Desktop.
Save lsancho/7b21922547dbe867c357 to your computer and use it in GitHub Desktop.
Validates ISBN13 codes
/// <summary>
/// Validates ISBN13 codes
/// </summary>
/// <param name="isbn13">code to validate</param>
/// <returns>true, if valid</returns>
public static bool IsValidIsbn13(string isbn13)
{
if (string.IsNullOrEmpty(isbn13))
{
return false;
}
if (isbn13.Contains("-")) isbn13 = isbn13.Replace("-", "");
// If the length is not 13 or if it contains any non numeric chars, return false
long temp;
if (isbn13.Length != 13 || !long.TryParse(isbn13, out temp)) return false;
// Comment Source: Wikipedia
// The calculation of an ISBN-13 check digit begins with the first
// 12 digits of the thirteen-digit ISBN (thus excluding the check digit itself).
// Each digit, from left to right, is alternately multiplied by 1 or 3,
// then those products are summed modulo 10 to give a value ranging from 0 to 9.
// Subtracted from 10, that leaves a result from 1 to 10. A zero (0) replaces a
// ten (10), so, in all cases, a single check digit results.
var sum = 0;
for (var i = 0; i < 12; i++)
{
sum += int.Parse(isbn13[i].ToString()) * (i % 2 == 1 ? 3 : 1);
}
var remainder = sum % 10;
var checkDigit = 10 - remainder;
if (checkDigit == 10) checkDigit = 0;
var result = checkDigit == int.Parse(isbn13[12].ToString());
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment