1 21 22 package org.apache.commons.validator; 23 24 import org.apache.oro.text.perl.Perl5Util; 25 26 34 public class ISBNValidator { 35 36 private static final String SEP = "(\\-|\\s)"; 37 private static final String GROUP = "(\\d{1,5})"; 38 private static final String PUBLISHER = "(\\d{1,7})"; 39 private static final String TITLE = "(\\d{1,6})"; 40 private static final String CHECK = "([0-9X])"; 41 42 47 private static final String ISBN_PATTERN = 48 "/^" + GROUP + SEP + PUBLISHER + SEP + TITLE + SEP + CHECK + "$/"; 49 50 public ISBNValidator() { 51 super(); 52 } 53 54 64 public boolean isValid(String isbn) { 65 if (isbn == null || isbn.length() < 10 || isbn.length() > 13) { 66 return false; 67 } 68 69 if (isFormatted(isbn) && !isValidPattern(isbn)) { 70 return false; 71 } 72 73 isbn = clean(isbn); 74 if (isbn.length() != 10) { 75 return false; 76 } 77 78 return (sum(isbn) % 11) == 0; 79 } 80 81 84 private int sum(String isbn) { 85 int total = 0; 86 for (int i = 0; i < 9; i++) { 87 int weight = 10 - i; 88 total += (weight * toInt(isbn.charAt(i))); 89 } 90 total += toInt(isbn.charAt(9)); return total; 92 } 93 94 98 private String clean(String isbn) { 99 StringBuffer buf = new StringBuffer (10); 100 101 for (int i = 0; i < isbn.length(); i++) { 102 char digit = isbn.charAt(i); 103 if (Character.isDigit(digit) || (digit == 'X')) { 104 buf.append(digit); 105 } 106 } 107 108 return buf.toString(); 109 } 110 111 115 private int toInt(char ch) { 116 return (ch == 'X') ? 10 : Character.getNumericValue(ch); 117 } 118 119 123 private boolean isFormatted(String isbn) { 124 return ((isbn.indexOf('-') != -1) || (isbn.indexOf(' ') != -1)); 125 } 126 127 130 private boolean isValidPattern(String isbn) { 131 return new Perl5Util().match(ISBN_PATTERN, isbn); 132 } 133 134 } 135 | Popular Tags |