isbn.js 3.4 KB

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