A REST API endpoint that validates credit/debit card numbers using the Luhn algorithm (mod 10).
- Card Number Validation: Validates card numbers using the Luhn algorithm
- Card Type Detection: Identifies card types (Visa, Mastercard, American Express, Discover)
- Input Sanitization: Handles card numbers with spaces and dashes
- Input Validation: Proper error handling for invalid inputs
- Node.js with TypeScript
- Express.js
- Jest for testing
card-number-validation-api/
├── src/
│ ├── index.ts # Express app and API endpoint
│ ├── cardValidator.ts # Card validation logic (Luhn algorithm)
│ ├── cardValidator.test.ts # Unit tests
│ └── types.ts # TypeScript interfaces
├── package.json
├── tsconfig.json
├── jest.config.js
└── README.md
- Install dependencies:
npm installnpm run devThe server will start on http://localhost:3000
npm run build
npm startnpm testValidates a card number and returns the validation result.
{
"cardNumber": "4111111111111111"
}{
"valid": true,
"cardNumber": "4111111111111111",
"message": "Valid card number",
"cardType": "Visa"
}{
"valid": false,
"cardNumber": "4111111111111112",
"message": "Invalid card number (failed Luhn check)",
"cardType": "Visa"
}{
"error": "Bad Request",
"message": "Card number is required"
}The API uses the Luhn algorithm (also known as mod 10) to validate card numbers. This is the industry-standard algorithm used by most payment processors to verify card numbers before processing.
- Card numbers can be submitted with or without spaces (e.g.,
4111 1111 1111 1111) - Card numbers can include dashes (e.g.,
4111-1111-1111-1111) - The API automatically sanitizes input before validation
- 200 OK: Card number is valid
- 400 Bad Request: Missing or invalid input (e.g., missing card number field)
- 422 Unprocessable Entity: Card number is present but invalid (fails validation)
- 500 Internal Server Error: Unexpected server error
The API can identify the following card types based on the card number prefix:
- Visa: Starts with 4
- Mastercard: Starts with 51-55 or 2221-2720
- American Express: Starts with 34 or 37
- Discover: Starts with 6011, 644-649, or 65
Card numbers must be between 13 and 19 digits (standard for most card types).
The project includes unit tests for the CardValidator class covering:
- Valid card numbers (Visa, Mastercard, American Express)
- Invalid card numbers (failed Luhn check)
- Non-digit characters
- Invalid lengths (too short or too long)
- Card type detection
npm install
npm run build
npm test
npm run dev