开发者

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

I was wonder is a there a w开发者_高级运维eb 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


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;
}


you might try:

http://isbndb.com/docs/api/


You could calc the checksum according to this algorithm: http://en.wikipedia.org/wiki/International_Standard_Book_Number#Check_digits. That doesn't tell you if there is actually a book with that number but it tells you if the number is correct.


Gory details here. So you can check the check digit and have a go at deducing what the country (and maybe publisher) are, but I don't see any way of checking there's a real book with that number


To validate just the checkdigit, and not compare against a known list of books, you could use the Apache Commons ISBNValidator class.

ISBNValidator validator = new ISBNValidator(); 
assertFalse(validator.isValid("12345678901234")); 
assertTrue(validator.isValid("0-201-63385-X"));

Code example from: https://apache.googlesource.com/commons-validator/+/trunk/src/test/java/org/apache/commons/validator/ISBNValidatorTest.java

References: https://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/ISBNValidator.html


As others have suggested in my quick searches on SO try: idbndb

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜