Archive for August 2009
Here’s a quick Javascript I wrote to validate (The 4 major American) credit card numbers, based on this post by Harrell W. Stiles.
Validate a credit card number with Javascript.
View the source on that page to grab the code, here are the two main functions as a quick reference:
function get_cc_type(n){
var n2 = n.substr(0,2);
var n4 = n.substr(0,4);
var n1 = n.substr(0,1);
var l = n.length
if(n4 == "6011" && l == 16){
return "discover";
} else if(n1 == "4" && l > 12 && l < 17){
return "visa";
} else if(n2 == "51" || n2 == "52" || n2 == "53" || n2 == "54" || n2 == "55" && l == 16){
return "mastercard";
} else if(n2 == "34" || n2 == "37" && l == 15){
return "american_express";
} else {
return "unknown";
}
}
function is_valid_cc_number(n){
var toggle = 0;
var total = 0;
n = n.split("").reverse();
for(i=0;i<n.length;i++){
if(toggle == 0){
val = n[i];
toggle = 1;
} else {
val = n[i] * 2;
if(val > 9){
tempVal = val.toString().split("");
val = parseInt(tempVal[0]) + parseInt(tempVal[1]);
}
toggle = 0;
}
total = parseInt(total) + parseInt(val);
}
if(total % 10 === 0){
return true;
} else {
return false;
}
}
No tags
