isCreditCard.js 1022 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import assertString from './util/assertString';
  2. /* eslint-disable max-len */
  3. 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}))$/;
  4. /* eslint-enable max-len */
  5. export default function isCreditCard(str) {
  6. assertString(str);
  7. var sanitized = str.replace(/[- ]+/g, '');
  8. if (!creditCard.test(sanitized)) {
  9. return false;
  10. }
  11. var sum = 0;
  12. var digit;
  13. var tmpNum;
  14. var shouldDouble;
  15. for (var i = sanitized.length - 1; i >= 0; i--) {
  16. digit = sanitized.substring(i, i + 1);
  17. tmpNum = parseInt(digit, 10);
  18. if (shouldDouble) {
  19. tmpNum *= 2;
  20. if (tmpNum >= 10) {
  21. sum += tmpNum % 10 + 1;
  22. } else {
  23. sum += tmpNum;
  24. }
  25. } else {
  26. sum += tmpNum;
  27. }
  28. shouldDouble = !shouldDouble;
  29. }
  30. return !!(sum % 10 === 0 ? sanitized : false);
  31. }