isbn.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. (function($) {
  2. $.fn.bootstrapValidator.validators.isbn = {
  3. /**
  4. * Return true if the input value is a valid ISBN 10 or ISBN 13 number
  5. * Examples:
  6. * - Valid:
  7. * ISBN 10: 99921-58-10-7, 9971-5-0210-0, 960-425-059-0, 80-902734-1-6, 85-359-0277-5, 1-84356-028-3, 0-684-84328-5, 0-8044-2957-X, 0-85131-041-9, 0-943396-04-2, 0-9752298-0-X
  8. * ISBN 13: 978-0-306-40615-7
  9. * - Invalid:
  10. * ISBN 10: 99921-58-10-6
  11. * ISBN 13: 978-0-306-40615-6
  12. *
  13. * @see http://en.wikipedia.org/wiki/International_Standard_Book_Number
  14. * @param {BootstrapValidator} validator The validator plugin instance
  15. * @param {jQuery} $field Field element
  16. * @param {Object} options Can consist of the following keys:
  17. * - message: The invalid message
  18. * @returns {Boolean}
  19. */
  20. validate: function(validator, $field, options) {
  21. var value = $field.val();
  22. if (value == '') {
  23. return true;
  24. }
  25. // http://en.wikipedia.org/wiki/International_Standard_Book_Number#Overview
  26. // Groups are separated by a hyphen or a space
  27. var type;
  28. switch (true) {
  29. case /^\d{9}[\dX]$/.test(value):
  30. case (value.length == 13 && /^(\d+)-(\d+)-(\d+)-([\dX])$/.test(value)):
  31. case (value.length == 13 && /^(\d+)\s(\d+)\s(\d+)\s([\dX])$/.test(value)):
  32. type = 'ISBN10';
  33. break;
  34. case /^(978|979)\d{9}[\dX]$/.test(value):
  35. case (value.length == 17 && /^(978|979)-(\d+)-(\d+)-(\d+)-([\dX])$/.test(value)):
  36. case (value.length == 17 && /^(978|979)\s(\d+)\s(\d+)\s(\d+)\s([\dX])$/.test(value)):
  37. type = 'ISBN13';
  38. break;
  39. default:
  40. return false;
  41. }
  42. // Replace all special characters except digits and X
  43. value = value.replace(/[^0-9X]/gi, '');
  44. var chars = value.split(''),
  45. length = chars.length,
  46. sum = 0,
  47. checksum;
  48. switch (type) {
  49. case 'ISBN10':
  50. sum = 0;
  51. for (var i = 0; i < length - 1; i++) {
  52. sum += ((10 - i) * parseInt(chars[i]));
  53. }
  54. checksum = 11 - (sum % 11);
  55. if (checksum == 11) {
  56. checksum = 0;
  57. } else if (checksum == 10) {
  58. checksum = 'X';
  59. }
  60. return (checksum + '' == chars[length - 1]);
  61. case 'ISBN13':
  62. sum = 0;
  63. for (var i = 0; i < length - 1; i++) {
  64. sum += ((i % 2 == 0) ? parseInt(chars[i]) : (parseInt(chars[i]) * 3));
  65. }
  66. checksum = 10 - (sum % 10);
  67. if (checksum == 10) {
  68. checksum = '0';
  69. }
  70. return (checksum + '' == chars[length - 1]);
  71. default:
  72. return false;
  73. }
  74. }
  75. };
  76. }(window.jQuery));