cusip.js 2.0 KB

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