diff --git a/package.json b/package.json index f6fd07a..ee0c1a8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "xendit-js-node", - "version": "0.2.0", + "version": "0.3.0", "description": "JS client library for tokenizing credit cards as node modules", "main": "./src/xendit.js", "repository": { diff --git a/src/utils/credit_card_util.js b/src/utils/credit_card_util.js index e388cd0..3fbeb3f 100644 --- a/src/utils/credit_card_util.js +++ b/src/utils/credit_card_util.js @@ -18,7 +18,8 @@ CreditCardUtil.isCreditCardNumberValid = function (creditCardNumber) { return NUMBER_REGEX.test(creditCardNumber) && creditCardNumber.length >= 12 && creditCardNumber.length <= 19 && - CreditCardUtil.getCardType(creditCardNumber) !== null; + CreditCardUtil.getCardType(creditCardNumber) !== null && + CreditCardUtil.isValidLuhnNumber(creditCardNumber); }; CreditCardUtil.isCreditCardExpirationDateValid = function (cardExpirationMonth, cardExpirationYear) { @@ -51,6 +52,27 @@ CreditCardUtil.isCreditCardCVNValidForCardType = function (creditCardCVN, cardNu } }; +CreditCardUtil.isValidLuhnNumber = function (cardNumber) { + var sum = 0, bEven = false; + cardNumber = cardNumber.replace(/\D/g, ''); + + for (var n = cardNumber.length - 1; n >= 0; n--) { + var cDigit = cardNumber.charAt(n); + var nDigit = parseInt(cDigit, 10); + + if (bEven) { + if ((nDigit *= 2) > 9) { + nDigit -= 9; + } + } + + sum += nDigit; + bEven = !bEven; + } + + return (sum % 10) === 0; +}; + CreditCardUtil.getCardType = function (cardNumber) { if (cardNumber.indexOf('4') === 0) { if (CreditCardUtil._isCardVisaElectron(cardNumber)) {