An open API service indexing awesome lists of open source software.

https://github.com/juspay/cards-validator

Simple card validator
https://github.com/juspay/cards-validator

Last synced: 6 months ago
JSON representation

Simple card validator

Awesome Lists containing this project

README

          

# ๐Ÿ’ณ Cards Validator

### A comprehensive JS/TS library for validating credit and debit card numbers

[![npm version](https://img.shields.io/npm/v/@juspay/cards-validator.svg)](https://www.npmjs.com/package/@juspay/cards-validator)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![Bundle Size](https://img.shields.io/bundlephobia/minzip/@juspay/cards-validator)](https://bundlephobia.com/package/@juspay/cards-validator)

---

## โœจ Features

๐ŸŽฏ **Card Type Detection**
Automatically detects 12+ major card types including Visa, MasterCard, American Express, Discover, JCB, Maestro, RuPay, UnionPay, and more

โœ… **Luhn Algorithm Validation**
Implements the industry-standard Luhn algorithm for card number validation

๐Ÿ“ **Length Validation**
Validates card number length based on card type specifications

๐Ÿ”ข **CVV Length Information**
Provides valid CVV lengths for each detected card type

๐ŸŽจ **Range-based Detection**
Uses both regex patterns and BIN ranges for accurate card type identification

๐Ÿ“˜ **TypeScript Support**
Fully typed with comprehensive type definitions

โšก **Zero Dependencies**
Lightweight library with no external dependencies

## ๐Ÿ’ณ Supported Card Types

Click to view all supported card types

| ๐Ÿฆ Card Type | ๐Ÿ” Pattern/Range | ๐Ÿ“ Valid Lengths | ๐Ÿ”ข CVV Length |
|--------------|------------------|------------------|---------------|
| ๐Ÿ”ต Visa | `^4` | 16 | 3 |
| ๐Ÿ”ด MasterCard | BIN ranges 222100-272099, 510000-559999 | 16 | 3 |
| ๐Ÿ”ต American Express | `^3[47]` | 15 | 4 |
| ๐ŸŸ  Discover | `^(6011\|622...)` | 16 | 3 |
| ๐ŸŸข JCB | `^35(2[89]\|[3-8][0-9])` | 16 | 3 |
| ๐Ÿ”ด Maestro | `^(5018\|5081\|...)` | 12-19 | 0, 3 |
| ๐ŸŸฃ RuPay | BIN ranges | 16 | 3 |
| ๐Ÿ”ต UnionPay | `^6[0289]\|9[0245689]...` | 16-19 | 3 |
| โšช Diners Club | `^30[0-5]`, `^3([689]\|09)` | 14 | 3 |
| ๐ŸŸข Laser | `^(6304\|670[69]\|6771)` | 16-19 | 3, 4 |
| ๐Ÿ”ต Visa Electron | `^(4026\|417500\|...)` | 16 | 3 |
| ๐ŸŸ  Sodexo | `^(637513)` | 16 | 3 |

---

## ๐Ÿ“ฆ Installation

```bash
npm install @juspay/cards-validator
```

**Alternative package managers:**

```bash
# Using Yarn
yarn add @juspay/cards-validator

# Using pnpm
pnpm add @juspay/cards-validator
```

---

## ๐Ÿš€ Usage

### ๐ŸŽฏ Basic Usage

```typescript
import CardValidator from '@juspay/cards-validator';

// Create a new validator instance
const validator = new CardValidator('4111111111111111');

// Get card validation details
const result = validator.getCardDetails();

console.log(result);
// Output:
// {
// card_type: 'visa',
// valid: true,
// luhn_valid: true,
// length_valid: true,
// cvv_length: [3],
// supported_lengths: [16]
// }
```

### ๐Ÿ”ง Advanced Usage

```typescript
import CardValidator, { CardDetails } from '@juspay/cards-validator';

// Validate different card types
const cards = [
'4111111111111111', // Visa
'5555555555554444', // MasterCard
'378282246310005', // American Express
'6011111111111117', // Discover
];

cards.forEach(cardNumber => {
const validator = new CardValidator(cardNumber);
const result: CardDetails = validator.getCardDetails();

console.log(`Card: ${cardNumber}`);
console.log(`Type: ${result.card_type}`);
console.log(`Valid: ${result.valid}`);
console.log(`CVV Length: ${result.cvv_length.join(', ')}`);
console.log('---');
});
```

### ๐Ÿ”„ Handling Spaces and Dashes

The library automatically normalizes card numbers by removing spaces and dashes:

```typescript
const validator1 = new CardValidator('4111 1111 1111 1111');
const validator2 = new CardValidator('4111-1111-1111-1111');
const validator3 = new CardValidator('4111111111111111');

// All three will produce the same result
console.log(validator1.getCardDetails().valid); // true
console.log(validator2.getCardDetails().valid); // true
console.log(validator3.getCardDetails().valid); // true
```

---

## ๐Ÿ“š API Reference

### ๐Ÿ—๏ธ CardValidator Class

#### Constructor

```typescript
new CardValidator(cardNumber: string)
```

- `cardNumber`: The credit card number to validate (string)

#### Methods

##### ๐Ÿ“‹ `getCardDetails(): CardDetails`

Returns a comprehensive validation result object.

---

### ๐Ÿ“ Types

#### ๐Ÿ“Š `CardDetails`

```typescript
interface CardDetails {
card_type: string; // Detected card type (e.g., 'visa', 'mastercard', 'amex', 'unknown')
valid: boolean; // Overall validity (luhn_valid && length_valid)
luhn_valid: boolean; // Whether card passes Luhn algorithm check
length_valid: boolean; // Whether card length is valid for detected type
cvv_length: number[]; // Valid CVV lengths for this card type, e.g., [3] or [3, 4]
supported_lengths: number[]; // Valid card number lengths, e.g., [16] or [12,13,14,15,16,17,18,19]
}
```

#### ๐Ÿ’ณ `CardType`

```typescript
interface CardType {
name: string;
valid_length: number[];
cvv_length: number[];
pattern?: RegExp; // For pattern-based detection
range?: number[][]; // For BIN range-based detection
gaps?: number[]; // Optional: for formatting (e.g., Sodexo)
}
```

---

## ๐Ÿ’ก Examples

### ๐ŸŽจ Validate and Format Card Information

```typescript
import CardValidator from '@juspay/cards-validator';

function formatCardInfo(cardNumber: string) {
const validator = new CardValidator(cardNumber);
const result = validator.getCardDetails();

if (result.valid) {
return {
isValid: true,
cardType: result.card_type.replace('_', ' ').toUpperCase(),
cvvLength: result.cvv_length,
message: `Valid ${result.card_type} card`
};
} else {
return {
isValid: false,
cardType: result.card_type,
issues: [
!result.luhn_valid && 'Invalid checksum',
!result.length_valid && 'Invalid length'
].filter(Boolean),
message: 'Invalid card number'
};
}
}

// Examples
console.log(formatCardInfo('4111111111111111'));
// { isValid: true, cardType: 'VISA', cvvLength: [3], message: 'Valid visa card' }

console.log(formatCardInfo('4111111111111112'));
// { isValid: false, cardType: 'visa', issues: ['Invalid checksum'], message: 'Invalid card number' }
```

---

## ๐Ÿ› ๏ธ Development

### โš™๏ธ Prerequisites

- Node.js (version 14 or higher)
- npm, yarn, or pnpm

### ๐Ÿ”ง Setup

```bash
# Clone the repository
git clone https://github.com/juspay/cards-validator.git
cd cards-validator

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Run development mode with watch
npm run dev
```

### ๐Ÿ“œ Scripts

| Script | Description |
|--------|-------------|
| `npm run build` | ๐Ÿ”จ Compile TypeScript to JavaScript |
| `npm run dev` | ๐Ÿ‘€ Watch mode for development |
| `npm test` | ๐Ÿงช Run test suite |
| `npm run clean` | ๐Ÿงน Remove build artifacts |
| `npm run lint` | ๐Ÿ” Run ESLint |
| `npm run format` | โœจ Format code with Prettier |

---

## ๐Ÿงช Testing

The library includes comprehensive tests covering:

โœ… Card type detection for all supported card types
โœ… Luhn algorithm validation
โœ… Length validation
โœ… Edge cases and error handling
โœ… Input normalization (spaces, dashes)

Run tests with:

```bash
npm test
```

---

## ๐Ÿค Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## ๐Ÿ“„ License

This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.

---

## ๐Ÿ“‹ Changelog

### v0.1.0
- โœจ Initial release
- ๐Ÿ’ณ Support for 12+ major card types
- โœ… Luhn algorithm validation
- ๐Ÿ“ Length validation
- ๐Ÿ“˜ TypeScript support
- ๐Ÿงช Comprehensive test suite

---

## ๐Ÿ™ Acknowledgments

- ๐Ÿ” [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) for card number validation
- ๐Ÿ’ณ Card type patterns and ranges based on industry standards
- ๐ŸŒŸ Inspired by various open-source card validation libraries

---

## ๐Ÿ“ž Support

If you encounter any issues or have questions, please file an issue on the [GitHub repository](https://github.com/juspay/cards-validator/issues).

---

Made with โค๏ธ by [Juspay Technologies](https://juspay.in)

โญ Star us on [GitHub](https://github.com/juspay/cards-validator) โ€” it helps us grow!