cusip.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. (function($) {
  2. $.fn.bootstrapValidator.validators.cusip = {
  3. /**
  4. * Validate a CUSIP
  5. * Examples:
  6. * - Valid: 037833100, 931142103, 14149YAR8, 126650BG6
  7. * - Invalid: 31430F200, 022615AC2
  8. *
  9. * @see http://en.wikipedia.org/wiki/CUSIP
  10. * @param {BootstrapValidator} validator The validator plugin instance
  11. * @param {jQuery} $field Field element
  12. * @param {Object} options Can consist of the following keys:
  13. * - message: The invalid message
  14. * @returns {Boolean}
  15. */
  16. validate: function(validator, $field, options) {
  17. var value = $field.val();
  18. if (value == '') {
  19. return true;
  20. }
  21. value = value.toUpperCase();
  22. if (!/^[0-9A-Z]{9}$/.test(value)) {
  23. return false;
  24. }
  25. var converted = $.map(value.split(''), function(item) {
  26. var code = item.charCodeAt(0);
  27. return (code >= 'A'.charCodeAt(0) && code <= 'Z'.charCodeAt(0))
  28. // Replace A, B, C, ..., Z with 10, 11, ..., 35
  29. ? (code - 'A'.charCodeAt(0) + 10)
  30. : item;
  31. }),
  32. length = converted.length,
  33. sum = 0;
  34. for (var i = 0; i < length - 1; i++) {
  35. var num = parseInt(converted[i]);
  36. if (i % 2 != 0) {
  37. num *= 2;
  38. }
  39. if (num > 9) {
  40. num -= 9;
  41. }
  42. sum += num;
  43. }
  44. sum = (10 - (sum % 10)) % 10;
  45. return sum == converted[length - 1];
  46. }
  47. };
  48. }(window.jQuery));