Neil Ang

Bersonal Plog

A stunning likeness of Neil Ang
Super Nerd

How to validate an ISBN in JavaScript

Posted on .

The cool thing about an ISBN is that its last digit is a "check digit", which validates the rest of the number. How does it work? "It is calculated on a modulus 11 with weights 10-2, using X in lieu of 10 where ten would occur as a check digit." More info.

function isValidISBN (isbn) { 
  isbn = isbn.replace(/[^\dX]/gi, ''); 
  if(isbn.length != 10){ 
    return false; 
  } 
  var chars = isbn.split(''); 
  if(chars[9].toUpperCase() == 'X'){ 
    chars[9] = 10; 
  } 
  var sum = 0; 
  for (var i = 0; i < chars.length; i++) { 
    sum += ((10-i) * parseInt(chars[i])); 
  }; 
  return ((sum % 11) == 0); 
}