isCreditCard.js 1.3 KB

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