Is there a way to check if an ISBN number is a valid number before storing into the database

Thang Pham picture Thang Pham · Nov 24, 2010 · Viewed 8.4k times · Source

I was wonder is a there a web service or a database out there that let us programmatically check if the user input is an valid ISBN number before storing it in the database. Or is there a algorithm that allow the programmer to do that

Answer

Mike Caron picture Mike Caron · Nov 24, 2010

If look on the Wikipedia page, they have a simple algorithm to ensure than an ISBN is valid:

bool is_isbn_valid(char digits[10]) {
    int i, a = 0, b = 0;
    for (i = 0; i < 10; i++) {
        a += digits[i];  // Assumed already converted from ASCII to 0..9
        b += a;
    }
    return b % 11 == 0;
}

Of course, this doesn't ensure that it's real, only possible ;)

EDIT: This includes the ISBN 13 spec: (It's untested, and in the same pseudo-code as the wikipedia function)

bool is_valid_isbn(char isbn[]) {
    int sum = 0;
    if(isbn.length == 10) {
        for(int i = 0; i < 10; i++) {
            sum += i * isbn[i]; //asuming this is 0..9, not '0'..'9'
        }

        if(isbn[9] == sum % 11) return true;
    } else if(isbn.length == 13) {

        for(int i = 0; i < 12; i++) {
            if(i % 2 == 0) {
                sum += isbn[i]; //asuming this is 0..9, not '0'..'9'
            } else {
                sum += isbn[i] * 3;
            }
        }

        if(isbn[12] == 10 - (sum % 10)) return true;
    }

    return false;
}