Dispersion Design

< Back

Verifying 10-Digit ISBN Numbers

2014-03-11

Introduction

ISBN (International Standard Book Number) is the method for uniquely identifying a particular book. An ISBN can be 10 or 13 digits long, depending on the age of the book. Additionally, 9-digit SBNs were used prior to the development of the ISBN system.

Several checks can be performed on an ISBN to ensure that it is valid and has not been entered, copied or transmitted incorrectly. This article demonstrates how to verify a 10-digit ISBN.

Valid Character Sequences

10-digit ISBN numbers will be exactly 10 characters long and will only use the characters '0'–'9', except for the final character, which can also use the character 'X'.

An ISBN could be entered using additional characters—such as spaces, hyphens or underscores—to separate groups of numbers. For example:

0-689-85666-0
or
0 02 718350 5

So, the first step to verifying an ISBN is to normalize the string by removing invalid characters. We will also convert lowercase 'x' characters to uppercase 'X'. In JavaScript, this can be achieved using the following:

var str = '0-689-85666-0';

// Substitute 'x' with 'X'
str = str.replace(/x/g, 'X');

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

A 9-digit SBN can be converted to a 10-digit ISBN by prepending a '0':

// Check for 9-digit SBN
if (str.length === 9) {
	str = '0' + str;
}

Now, the ISBN strings can be verified using the following regular expression:

/^[0-9]{9}[0-9X]$/

In JavaScript, this regular expression is utilized with the match function:

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

Verifying the Check Digit

Finally, the check digit should be verified. Details on the check digit algorithm can be found on Wikipedia.

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

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

for (i = 0; i < 10; i += 1) {
	sum += (chars[i] === 'X' ? 10 : chars[i]) * (10 - i);
}

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

Putting it All Together

function verifyISBN10 (str) {
	str = str.replace(/x/g, 'X');
	str = str.replace(/[^0-9X]/g, '');
	if (str.length === 9) {
		str = '0' + str;
	}

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

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

	for (i = 0; i < 10; i += 1) {
		sum += (chars[i] === 'X' ? 10 : chars[i]) * (10 - i);
	}

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

Demo

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