A simple JavaScript tool to validate credit card numbers using the Luhn algorithm and detect the card type (e.g., Visa, Mastercard, American Express, Discover).
- Validates credit card numbers using the Luhn algorithm
- Detects card types:
- Visa
- Mastercard
- American Express
- Discover
- Auto-formats card number input with spaces (e.g.,
4111 1111 1111 1111
) - Includes test cases for validation accuracy
- Works entirely in the browser β no backend required
- Input Sanitization: Removes all non-digit characters from the card number.
- Length Check: Ensures the card number is exactly 16 digits.
- Luhn Algorithm: Validates the card number mathematically.
- Card Type Detection: Uses regex patterns to identify the card issuer.
- User Feedback: Displays validation result and card type on the page.
The script includes a small test suite that checks known valid and invalid card numbers and logs results to the browser console.
Example output in console:
Test 1: 4111 1111 1111 1111 => true (Expected: true) - PASS
Test 2: 5500 0000 0000 0004 => true (Expected: true) - PASS
...
To run this project:
- Save the code in an
.html
file. - Open it in any modern web browser.
- Enter a credit card number and click "Validate".
- View the result and card type on the screen.
- Open the browser console to see test results.
π‘ Tip: Use
F12
orCtrl+Shift+I
to open Developer Tools and view the console output.