How to check if an ISBN is valid in Perl or JavaScript
Posted: 5 June 2009
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.
Validate an ISBN in Perl
Here is a simple subroutine I wrote to check if a number entered is valid:
sub valid_isbn {
my $isbn = shift;
$isbn =~ s/[^\dX]//gi;
return if length($isbn) != 10;
my $sum = 0;
my @chars = split('', $isbn);
$chars[9] = 10 if uc($chars[9]) eq 'X';
for (my $char = 0; $char < @chars; $char++) {
$sum += (10-$char) * $chars[$char];
}
return (($sum % 11) == 0);
}
Code would not be complete without tests!
use Test::More tests => 12;
is(valid_isbn("ISBN 0843610727"), 1);
is(valid_isbn("99921-58-10-7"), 1);
is(valid_isbn("9971 5 0210 0"), 1);
is(valid_isbn("0-8044-2957-X"), 1);
is(valid_isbn("0943396042"), 1);
is(valid_isbn("0-9752298-0-X"), 1);
isnt(valid_isbn("ISBN 0843610723"), 1);
isnt(valid_isbn("91921-58-10-7"), 1);
isnt(valid_isbn("9971 5 0214 0"), 1);
isnt(valid_isbn("0-8044-2957-2"), 1);
isnt(valid_isbn("0943394042"), 1);
isnt(valid_isbn("0-9757297-0-X"), 1);
Validate an ISBN in JavaScript
And here it is written as a JavaScript function:
<script type="text/javascript" charset="utf-8">
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);
}
</script>
Post a comment
Comment Guidelines
- You can subscribe to the comments on this entry via RSS.
- Have no more than 2 links, otherwise your comment will be flagged as spam.
- Links are automagically generated.
- <em>text</em> to make text italic.
- <strong>text</strong> to make text bold.
JavaScript needs to be enabled to comment.
Your comments (subscribe)
Alexandr Ciornii 12 Jun 09 at 9:46pm
Of course there is module on CPAN for ISBN's: Business::ISBN Perl module.
Alexandr Ciornii 12 Jun 09 at 9:46pm
Test::More can be used for testing Perl programs and port of can be used in JavaScript: Test.More.
Neil 25 Jun 09 at 9:16pm
@Alexandr thanks. I updated the test to Test::More
Jessie Morris 13 Oct 09 at 9:15am
Thanks for the Javascript function! This will definitely be useful to me in the bookmarklet I'm going to write.