Closed fballiano closed 1 month ago
I asked Google Gemini to code:
function validateCreditCardNumber(inputString) {
// Remove non-numeric characters from the input string
const sanitizedString = inputString.replace(/\D/g, "");
// Check for empty string or all repeated digits
if (!sanitizedString || sanitizedString.split("").every(char => char === sanitizedString[0])) {
return false;
}
// Check the length based on common card lengths
const validLengths = [13, 15, 16];
if (!validLengths.includes(sanitizedString.length)) {
return false;
}
// Check the starting digits based on common card issuers
const validStartingDigits = {
"4": [ // Visa
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49"
],
"5": [ // MasterCard
"51", "52", "53", "54", "55"
],
"3": [ // American Express, Diners Club
"34", "37" // Amex
// "300", "305", "36", "38" // Diners Club (potentially not widely used)
],
"6": [ // Discover
"6011", "622126", "622925", "644", "645", "646", "647", "648", "649",
"65"
]
};
const firstDigit = sanitizedString.charAt(0);
const startingDigits = sanitizedString.substring(0, 2);
if (!Object.keys(validStartingDigits).includes(firstDigit) ||
!validStartingDigits[firstDigit].includes(startingDigits)) {
return false;
}
let sum = 0;
let isDouble = false;
// Iterate through the digits from the rightmost side
for (let i = sanitizedString.length - 1; i >= 0; i--) {
let digit = parseInt(sanitizedString.charAt(i));
// Double every second digit (starting from the rightmost)
if (isDouble) {
digit *= 2;
// If the doubled digit is greater than 9, add the digits individually
if (digit > 9) {
digit = 1 + (digit % 10);
}
}
sum += digit;
isDouble = !isDouble; // Toggle the doubling flag for the next iteration
}
// Check if the sum is a multiple of 10
return sum % 10 === 0;
}
Tested with real visa cards, amex, and master card. Also tested invalid number by editing the real ones.
@kiatng no man that's done in another part of our codebase, the length and prefix check, that's precisely why I didn't change the logic and how the functions work.
again, prefix and length check is already done somewhere else.
check validate-cc-number in validation.js
This PR targets
next
We're this weird ccard.js file that has a weird copyright and the license is not clear, you can see that:
This seems to be copyrighted code and has to be removed from openmage
Credit cards use Luhn algothithm which is public domain.
This PR removes this file (a network connection just for a single javascript function is not a good idea) and reimplemented the validation method using the public domain code.