This repository has been archived by the owner on Nov 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
creditcard.go
98 lines (88 loc) · 1.93 KB
/
creditcard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
fmt.Println("Enter the credit card number to be validated: ")
in := bufio.NewReader(os.Stdin)
input, err := in.ReadString('\n')
if err != nil {
fmt.Println("Error:", err)
return
}
ccNum := make([]int, 19, 19)
i := 0
for _, rune := range input {
n, err := strconv.Atoi(string(rune))
if err == nil {
ccNum[i] = n
i++
}
}
ccNum = ccNum[:i]
valid, cardType := ValidateCreditCard(ccNum)
if valid && cardType != "Unknown" {
fmt.Printf("Credit card number is a valid %s card\n", cardType)
} else {
fmt.Println("Credit card number is NOT valid!")
}
}
func ValidateCreditCard(ccNum []int) (valid bool, cardType string) {
valid = luhnCheck(ccNum)
cardType = getCardType(ccNum)
return valid, cardType
}
func getCardType(ccNum []int) string {
var sArray = make([]string, len(ccNum))
for i, n := range ccNum {
sArray[i] = strconv.Itoa(n)
}
s := strings.Join(sArray, "")
match, _ := regexp.MatchString("^3[47][0-9]{13}$", s)
if match {
return "American Express"
}
match, _ = regexp.MatchString("^4[0-9]{12}(?:[0-9]{3})?$", s)
if match {
return "Visa"
}
match, _ = regexp.MatchString("^5[1-5][0-9]{14}$", s)
if match {
return "MasterCard"
}
match, _ = regexp.MatchString("^3(?:0[0-5]|[68][0-9])[0-9]{11}$", s)
if match {
return "Diners Club"
}
match, _ = regexp.MatchString("^6(?:011|5[0-9]{2})[0-9]{12}$", s)
if match {
return "Discover"
}
match, _ = regexp.MatchString("^(?:2131|1800|35[0-9]{3})[0-9]{11}$", s)
if match {
return "JCB"
}
return "Unknown"
}
func luhnCheck(ccNum []int) bool {
checksum := 0
for i, n := range ccNum {
if (i+len(ccNum)%2)%2 == 0 {
checksum += sumDigits(2 * n)
} else {
checksum += n
}
}
return checksum%10 == 0
}
func sumDigits(n int) int {
hundreds := n / 100
tens := (n - 100*hundreds) / 10
ones := n - 100*hundreds - 10*tens
return ones + tens + hundreds
}