Skip to content

Commit

Permalink
IsValid card options (#130)
Browse files Browse the repository at this point in the history
* feat: adding cards options to isValid method

* chore: additional tests and info in README

* fix: validating unsupported cards correctly

* chore: additional unsupported cards tests

Co-authored-by: Ciro Ferreira da Cruz <[email protected]>
  • Loading branch information
diogomqbm and cirocfc authored Feb 26, 2021
1 parent 1fe2331 commit ce71b4f
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 11 deletions.
24 changes: 15 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ $ npm install creditcard.js
## Usage

```javascript
import {
isValid,
isExpirationDateValid,
isSecurityCodeValid,
getCreditCardNameByNumber
import {
isValid,
isExpirationDateValid,
isSecurityCodeValid,
getCreditCardNameByNumber,
} from 'creditcard.js';

isValid('4916108926268679'); // returns true
Expand All @@ -52,7 +52,13 @@ Checks whether the credit card number format is valid. _(See the full list of [c
_Required_\
Type: `string`

-----
**options**

_Optional_\
Type: `{ cards: string[] } `

---

### `isExpirationDateValid(month, year)` -> `boolean`

Checks that the expiration date is valid and not expired. _(2 or 4 digit years are accepted)_
Expand All @@ -67,7 +73,7 @@ Type: `string`
_Required_\
Type: `string`

-----
---

### `isSecurityCodeValid(creditCardNumber, securityCode)` -> `boolean`

Expand All @@ -83,7 +89,7 @@ Type: `string`
_Required_\
Type: `string`

-----
---

### `getCreditCardNameByNumber(number)` -> `string`

Expand All @@ -94,7 +100,7 @@ Returns the credit card type from the card number. _(See the full list of [curre
_Required_\
Type: `string`

-----
---

## Suportted credit card types

Expand Down
22 changes: 20 additions & 2 deletions src/creditcard.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,33 @@ export const isExpirationDateValid = (month, year) => {
);
};

export const isValid = (number) => {
export const isValid = (number, options = {}) => {
const invalidDigits = new RegExp('[^0-9- ]');
const { cards } = options;

if (invalidDigits.test(number)) return false;

const sum = sumNumber(number.replace(/\D/g, ''));
return sum > 0 && sum % 10 === 0;
const sumIsOk = sum > 0 && sum % 10 === 0;

if (cards && cards.length) {
return (
sumIsOk &&
areCardsSupported(cards) &&
cards
.map((c) => c.toLowerCase())
.includes(getCreditCardNameByNumber(number).toLowerCase())
);
}

return sumIsOk;
};

function areCardsSupported(passedCards) {
const supportedCards = CARDS.map((c) => c.name.toLowerCase());
return passedCards.every((c) => supportedCards.includes(c.toLowerCase()));
}

function findCreditCardObjectByNumber(number) {
if (!number) return {};
const numberOnly = number.replace(/[^\d]/g, '');
Expand Down
Loading

0 comments on commit ce71b4f

Please sign in to comment.