lmg
lmg

Reputation: 79

How do I check if an input contains an isbn using javascript

I need a script that will test an input field's contents to see if it contains an ISBN. I found a few examples of this, but none of them strip the dashes. I need this to happen or my search results don't work. I have the else part of the script working if the field doesn't have an ISBN, but can't get the ISBN test to work. Thank you in advance for any help!

function search() {
    var textboxdata = $('#search').val();
        if (textboxdata contains an ISBN number, strip it of dashes and) {
            // perform ISBN search
            document.location.href = "http://myurl?search=" + textboxdata;
        }
        else { //perform other search
        }
 }

Upvotes: 2

Views: 7209

Answers (4)

Derek Kurth
Derek Kurth

Reputation: 1898

Based on the algorithms given in the Wikipedia article, here's a simple javascript function for validating 10- and 13-digit ISBNs:

var isValidIsbn = function(str) {

    var sum,
        weight,
        digit,
        check,
        i;

    str = str.replace(/[^0-9X]/gi, '');

    if (str.length != 10 && str.length != 13) {
        return false;
    }

    if (str.length == 13) {
        sum = 0;
        for (i = 0; i < 12; i++) {
            digit = parseInt(str[i]);
            if (i % 2 == 1) {
                sum += 3*digit;
            } else {
                sum += digit;
            }
        }
        check = (10 - (sum % 10)) % 10;
        return (check == str[str.length-1]);
    }

    if (str.length == 10) {
        weight = 10;
        sum = 0;
        for (i = 0; i < 9; i++) {
            digit = parseInt(str[i]);
            sum += weight*digit;
            weight--;
        }
        check = (11 - (sum % 11)) % 11
        if (check == 10) {
            check = 'X';
        }
        return (check == str[str.length-1].toUpperCase());
    }
}

Upvotes: 8

Farnam
Farnam

Reputation: 11

Derek's code fails for this ISBN ==> "0756603390"

It's because the check digit will end up as 11.

incorrect == > check = 11 - (sum % 11); correct ==> check = (11 - (sum % 11)) %11;

I tested the new code against 500 ISBN10s.

Upvotes: 1

Andrew Cafourek
Andrew Cafourek

Reputation: 431

There is also a js library available for checking ISBN10 and ISBN13 formatting: isbnjs as well as isbn-verify


Edit 2/2/17 - previous link was to Google Code, some updated current links: - npm for isbn-verify - npm for isbnjs - Github project

Upvotes: 2

William Troup
William Troup

Reputation: 13131

Take a look at this Wikipedia article:

http://en.wikipedia.org/wiki/International_Standard_Book_Number

Should give you some insight into how to validate an ISBN number.

Upvotes: 1

Related Questions