Discussion on:
View:
Show:
Does not tak into account hyphens in the value or the X as a check Digit.
The code sample provided in the tip is not intended to be used in applications as is. It does however explain the basics of confirming an ISBN number is valid. You are welcome to modify it to best fit your needs.
How about this (C#) alternative:
static bool IsISBNValid(string sInput)
{
// remove delimiters
string sISBN = Regex.Replace(sInput, @"-|\.| ", "");
// validate number of digits
if (sISBN.Length != 10 && sISBN.Length != 13)
return false;
// calculate the product of the digit multiplication operations
int iProd = 0;
for (int i = 0; i (sISBN.Length - 1); i++)
{
if (sISBN.Length == 10)
iProd += Convert.ToInt16(sISBN.Substring(i, 1)) * (10 - i);
else
iProd += Convert.ToInt16(sISBN.Substring(i, 1)) * (1 + (2 * (i % 2)));
}
// calculate the check digit
string sCheckDigit;
if (sISBN.Length == 10)
{
sCheckDigit = Convert.ToString((11 - (iProd % 11)) % 11);
if (sCheckDigit == "10")
sCheckDigit = "X";
}
else
sCheckDigit = Convert.ToString(10 - (iProd % 10));
// validate check digit
return (sCheckDigit == sISBN.Substring(sISBN.Length - 1, 1));
}
static bool IsISBNValid(string sInput)
{
// remove delimiters
string sISBN = Regex.Replace(sInput, @"-|\.| ", "");
// validate number of digits
if (sISBN.Length != 10 && sISBN.Length != 13)
return false;
// calculate the product of the digit multiplication operations
int iProd = 0;
for (int i = 0; i (sISBN.Length - 1); i++)
{
if (sISBN.Length == 10)
iProd += Convert.ToInt16(sISBN.Substring(i, 1)) * (10 - i);
else
iProd += Convert.ToInt16(sISBN.Substring(i, 1)) * (1 + (2 * (i % 2)));
}
// calculate the check digit
string sCheckDigit;
if (sISBN.Length == 10)
{
sCheckDigit = Convert.ToString((11 - (iProd % 11)) % 11);
if (sCheckDigit == "10")
sCheckDigit = "X";
}
else
sCheckDigit = Convert.ToString(10 - (iProd % 10));
// validate check digit
return (sCheckDigit == sISBN.Substring(sISBN.Length - 1, 1));
}
ISBN uses the character "X" to represent the value 10. The example uses the Convert.ToInt32 method which will fail if "X" is passed as the arg.
-George Sheehy
-George Sheehy
Well, one could say that it does show rudimentary string conversion to numeric integers as it parses the string. As to "validation" of an ISBN number, it just validates that the string has numbers in it. To do a true validation, it would require more logic and much more code.
- Keyboard Shortcuts:
- Prev
- Next
- Toggle

































