4.13. Validate ISBNs
Problem
You need to check the validity of an International Standard Book Number
(ISBN), which can be in either the older ISBN-10 or the current
ISBN-13 format. You want to allow a leading ISBN identifier, and ISBN parts can
optionally be separated by hyphens or spaces. ISBN 978-0-596-52068-7,
ISBN-13:
978-0-596-52068-7, 978 0 596 52068 7, 9780596520687,
ISBN-10
0-596-52068-9, and 0-596-52068-9 are all examples of valid
input.
Solution
You cannot validate an ISBN using a regex alone, because the last digit is computed using a checksum algorithm. The regular expressions in this section validate the format of an ISBN, whereas the subsequent code examples include a validity check for the final digit.
Regular expressions
ISBN-10:
^(?:ISBN(?:-10)?:?●)?(?=[-0-9X●]{13}$|[0-9X]{10}$)[0-9]{1,5}[-●]?↵ (?:[0-9]+[-●]?){2}[0-9X]$
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
ISBN-13:
^(?:ISBN(?:-13)?:?●)?(?=[-0-9●]{17}$|[0-9]{13}$)97[89][-●]?[0-9]{1,5}↵ [-●]?(?:[0-9]+[-●]?){2}[0-9]$
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
ISBN-10 or ISBN-13:
^(?:ISBN(?:-1[03])?:?●)?(?=[-0-9●]{17}$|[-0-9X●]{13}$|[0-9X]{10}$)↵ (?:97[89][-●]?)?[0-9]{1,5}[-●]?(?:[0-9]+[-●]?){2}[0-9X]$
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
JavaScript
// `regex` checks for ISBN-10 or ISBN-13 format var regex = /^(?:ISBN(?:-1[03])?:? )?(?=[-0-9 ]{17}$|[-0-9X ]{13}$|↵ [0-9X]{10}$)(?:97[89][- ]?)?[0-9]{1,5}[- ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access