isCreditCard.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = isCreditCard;
  6. var _assertString = require('./util/assertString');
  7. var _assertString2 = _interopRequireDefault(_assertString);
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. /* eslint-disable max-len */
  10. var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|62[0-9]{14}$/;
  11. /* eslint-enable max-len */
  12. function isCreditCard(str) {
  13. (0, _assertString2.default)(str);
  14. var sanitized = str.replace(/[^0-9]+/g, '');
  15. if (!creditCard.test(sanitized)) {
  16. return false;
  17. }
  18. var sum = 0;
  19. var digit = void 0;
  20. var tmpNum = void 0;
  21. var shouldDouble = void 0;
  22. for (var i = sanitized.length - 1; i >= 0; i--) {
  23. digit = sanitized.substring(i, i + 1);
  24. tmpNum = parseInt(digit, 10);
  25. if (shouldDouble) {
  26. tmpNum *= 2;
  27. if (tmpNum >= 10) {
  28. sum += tmpNum % 10 + 1;
  29. } else {
  30. sum += tmpNum;
  31. }
  32. } else {
  33. sum += tmpNum;
  34. }
  35. shouldDouble = !shouldDouble;
  36. }
  37. return !!(sum % 10 === 0 ? sanitized : false);
  38. }
  39. module.exports = exports['default'];