To validate a credit card number in JavaScript we will use regular expression combined with Luhn's algorithm. Appling Luhn's algorithm to perform a checksum validation for added security
Luhn algorithm:
- It first sanitizes the input by removing any non-digit characters (e.g., spaces).
- It then processes the digits from the end, doubling every second digit, and subtracting 9 if the doubled value is greater than 9.
- The sum of all digits is calculated, and if the sum is divisible by 10, the card is valid.
function validCard(n) {
// Remove all non-num characters (e.g., spaces or hyphens)
const s = n.replace(/[^0-9]/g, '');
// Check if the input length is valid (most cards have between 13 and 19 nums)
if (s.length < 13 || s.length > 19) {
return false;
}
let sum = 0;
let sd = false;
// Loop through the card number nums, starting from the last num
for (let i = s.length - 1; i >= 0; i--) {
let num = parseInt(s[i], 10);
if (sd) {
num *= 2;
if (num > 9) {
num -= 9; // If the result is a two-num number, subtract 9
}
}
sum += num;
sd = !sd; // Toggle the doubling
}
// If the total sum is divisible by 10, it's a valid card number
return sum % 10 === 0;
}
const n = '4539 1488 0343 6467'; // Example Visa number
if (validCard(n)) {
console.log('Valid credit card number.');
} else {
console.log('Invalid credit card number.');
}
Output
Valid credit card number.
Luhn algorithm validates only the format. But How to check on the card was from which company.
Determining the Credit Card Issuer
function getIssuer(num) {
// Remove all non-digit characters (e.g., spaces or hyphens)
const s = num.replace(/[^0-9]/g, '');
// Check the length of the card number
if (s.length < 13 || s.length > 19) {
return 'Invalid card length';
}
// Determine the card issuer
if (/^4/.test(s)) {
return 'Visa';
} else if (/^5[1-5]/.test(s)) {
return 'MasterCard';
} else if (/^3[47]/.test(s)) {
return 'American Express';
} else if (/^6(?:011|5)/.test(s)) {
return 'Discover';
} else if (/^3(?:0[0-5]|[68])/.test(s)) {
return 'Diners Club';
} else if (/^35/.test(s)) {
return 'JCB';
} else {
return 'Unknown issuer';
}
}
const num = '4111 1111 1111 1111';
console.log(`The card issuer is: ${getIssuer(num)}`);
Output
The card issuer is: Visa
Explanation credit card issuer:
- Visa cards start with the digit 4.
- Master Card cards typically start with numbers ranging from 51 to 55.
- American Express (Amex) cards start with 34 or 37.
- Discover cards may start with 6011 or have other prefixes starting with 65.
- Diners Club cards can start with specific ranges such as 300-305, 36, or 38.
- JCB cards often start with 35.