0

Card number validator in JavaScript

JavaScript
const validateCreditCardNumber = (value) => {
  	// accept only digits, dashes or spaces
	if (/[^0-9-\s]+/.test(value)) return false;

	// The Luhn Algorithm. 
	let nCheck = 0;
  	let nDigit = 0;
  	let bEven = false;
  
	value = value.replace(/\D/g, "");

	for (let n = value.length - 1; n >= 0; n--) {
		let cDigit = value.charAt(n);
		let nDigit = parseInt(cDigit, 10);

		if (bEven) {
			if ((nDigit *= 2) > 9) nDigit -= 9;
		}

		nCheck += nDigit;
		bEven = !bEven;
	}

	return (nCheck % 10) == 0;
}

// Test
console.log(validateCreditCardNumber('378282246310005')); // American Express
console.log(validateCreditCardNumber('371449635398431')); // American Express
console.log(validateCreditCardNumber('378734493671000')); // American Express Corporate
console.log(validateCreditCardNumber('5610591081018250')); // Australian BankCard
console.log(validateCreditCardNumber('30569309025904')); // Diners Club
console.log(validateCreditCardNumber('38520000023237')); // Diners Club
console.log(validateCreditCardNumber('6011111111111117')); // Discover
console.log(validateCreditCardNumber('6011000990139424')); // Discover
console.log(validateCreditCardNumber('3530111333300000')); // JCB
console.log(validateCreditCardNumber('3566002020360505')); // JCB
console.log(validateCreditCardNumber('5555555555554444')); // MasterCard
console.log(validateCreditCardNumber('5105105105105100')); // MasterCard
console.log(validateCreditCardNumber('4111111111111111')); // Visa
console.log(validateCreditCardNumber('4012888888881881')); // Visa
console.log(validateCreditCardNumber('4222222222222')); // Visa
console.log(validateCreditCardNumber('5019717010103742')); // Dankort (PBS)
console.log(validateCreditCardNumber('6331101999990016')); // Switch/Solo (Paymentech)
RUN
add comment
Suggest a different solution or add another example