1 function isValidCreditCard(type, ccnum) {
2 if (type == "Visa") {
3 // Visa: length 16, prefix 4, dashes optional.
4 var re = /^4d{3}-?d{4}-?d{4}-?d{4}$/;
5 } else if (type == "MC") {
6 // Mastercard: length 16, prefix 51-55, dashes optional.
7 var re = /^5[1-5]d{2}-?d{4}-?d{4}-?d{4}$/;
8 } else if (type == "Disc") {
9 // Discover: length 16, prefix 6011, dashes optional.
10 var re = /^6011-?d{4}-?d{4}-?d{4}$/;
11 } else if (type == "AmEx") {
12 // American Express: length 15, prefix 34 or 37.
13 var re = /^3[4,7]d{13}$/;
14 } else if (type == "Diners") {
15 // Diners: length 14, prefix 30, 36, or 38.
16 var re = /^3[0,6,8]d{12}$/;
17 }
18 if (!re.test(ccnum)) return false;
19 // Remove all dashes for the checksum checks to eliminate negative numbers
20 ccnum = ccnum.split("-").join("");
21 // Checksum ("Mod 10")
22 // Add even digits in even length strings or odd digits in odd length strings.
23 var checksum = 0;
24 for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
25 checksum += parseInt(ccnum.charAt(i-1));
26 }
27 // Analyze odd digits in even length strings or even digits in odd length strings.
28 for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
29 var digit = parseInt(ccnum.charAt(i-1)) * 2;
30 if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
31 }
32 if ((checksum % 10) == 0) return true; else return false;
33 }
完整的JavaScript版的信用卡校验代码