Dispersion Design

< Back

Verifying 13-Digit ISBN Numbers

2014-03-12

Introduction

A book can be identified by its ISBN (International Standard Book Number), a unique 10 or 13 digit string. Older books use a 10-digit value (ISBN-10) and newer books use 13-digits (ISBN-13). An ISBN-10 can also be easily converted to an ISBN-13.

This article shows how an ISBN-13, or 13-digit ISBN, can be verified to ensure that it is valid.

Valid Character Sequences

Obviously, a 13-digit ISBN should be 13 characters long, however it could have been entered using additional characters—such as spaces, hyphens or underscores—to separate groups of numbers. For example:

978-0-689-85666-2
or
978 0 689 85666 2

So, the ISBN-10 should first be normalized, removing additional characters. The only valid characters are '0'–'9'. This can be written in JavaScript as:

// Remove invalid characters
str = str.replace(/[^0-9]/g, '');

Now, we must check to make sure that there are exactly 13 characters remaining in the string. Additionally, an ISBN-13 will always start with "978" or "989". These checks can be implemented using a regular expression match:

if (!str.match(/^97[89][0-9]{10}$/)) {
	return 0;
}

Verifying the Check Digit

The final digit in the ISBN-13 is a check digit, used to verify that no other digits have been accidentally modified. Details about the check digit algorithm can be found on Wikipedia.

Implemented in JavaScript, the check digit verification can be written:

var chars = str.split("");

var sum = 0;
var i = 0;

for (i = 0; i < 13; i += 1) {
	sum += chars[i] * ((i % 2) ? 3 : 1);
}

if (sum % 10 != 0) {
	return 0;
}

Putting it All Together

All these verification steps can be combined into a single function:

function verifyISBN13 (str) {
	str = str.replace(/[^0-9]/g, '');

	if (!str.match(/^97[89][0-9]{10}$/)) {
		return 0;
	}

	var chars = str.split("");
	var sum = 0;
	var i = 0;

	for (i = 0; i < 13; i += 1) {
		sum += chars[i] * ((i % 2) ? 3 : 1);
	}

	if (sum % 10 !== 0) {
		return 0;
	}
	return str;
}

Demo

The following JavaScript demo verifies possible 13-digit ISBN strings entered into the input box: