Created
June 21, 2017 18:04
-
-
Save cristofer-dev/c4a5abdc28cca712982560bf58d32033 to your computer and use it in GitHub Desktop.
Validate credit card number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* cardNumber | |
* Recibe numero de tarjeta en int o str | |
* Return the true or false. | |
*/ | |
function cardNumber(num) { | |
num = num.toString(); | |
console.log('\nIn Function ' + num); | |
var visa = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/; | |
var mast = /^(?:5[1-5][0-9]{14})$/; | |
var amex = /^(?:3[47][0-9]{13})$/; | |
var disc = /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/; | |
var dine = /^(?:3(?:0[0-5]|[68][0-9])[0-9]{11})$/; | |
var jcb = /^(?:(?:2131|1800|35\d{3})\d{11})$/; | |
if(luhn_checksum(num) === true){ | |
if (num.match(visa)) console.log('VISA'); | |
if (num.match(mast)) console.log('MASTER'); | |
if (num.match(amex)) console.log('AMEX'); | |
if (num.match(disc)) console.log('DISC'); | |
if (num.match(dine)) console.log('Dinners'); | |
if (num.match(jcb)) console.log('JCB'); | |
}else{ | |
console.log("Número No valido"); | |
return "Numero No valido" | |
} | |
} | |
//Testing | |
cardNumber(5200828282828210)// Master | |
cardNumber('5555555555554444')// Amex | |
cardNumber('371449635398431')// Discover | |
cardNumber('6011000990139424')// Dinners | |
cardNumber('30569309025904')// JCB | |
cardNumber('3530111333300000')/* | |
/* luhn_checksum | |
* Implement the Luhn algorithm to calculate the Luhn check digit. | |
* Return the true or false. | |
*/ | |
function luhn_checksum(code) { | |
var len = code.length | |
var parity = len % 2 | |
var sum = 0 | |
for (var i = len - 1; i >= 0; i--) { | |
var d = parseInt(code.charAt(i)) | |
if (i % 2 == parity) { | |
d *= 2 | |
} | |
if (d > 9) { | |
d -= 9 | |
} | |
sum += d | |
} | |
return sum % 10 === 0 ? true : false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment