Skip to content

Instantly share code, notes, and snippets.

@lfaoro
Last active October 15, 2018 11:44
Show Gist options
  • Save lfaoro/1476e1e14a76fd8fa6bbbf3a164dd0cf to your computer and use it in GitHub Desktop.
Save lfaoro/1476e1e14a76fd8fa6bbbf3a164dd0cf to your computer and use it in GitHub Desktop.
// CreditCardRegex is the pattern used to identify a credit card PAN.
var CreditCardRegex = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$"
var rxCreditCard = regexp.MustCompile(CreditCardRegex)
var rxNotNumber = regexp.MustCompile("[^0-9]+")
// IsCreditCard checks if the string is a credit card.
func IsCreditCard(s string) bool {
sanitized := rxNotNumber.ReplaceAllString(s, "")
if !rxCreditCard.MatchString(sanitized) {
return false
}
return ValidLuhn(s)
}
// ValidLuhn returns true or false to indicate whether or not the supplied
// string of 2 or more digits passes or fails the Luhn check algorithm.
func ValidLuhn(number string) bool {
doubles := []int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}
matched, err := regexp.MatchString("^[[:digit:]]{2,}$", number)
if matched == false || err != nil {
return false
}
checkSum := 0
for i, double := len(number)-1, false; i >= 0; i-- {
if double {
checkSum += doubles[int(number[i]-'0')]
} else {
checkSum += int(number[i] - '0')
}
double = !double
}
return checkSum%10 == 0
}
@lfaoro
Copy link
Author

lfaoro commented Oct 15, 2018

https://gist.github.com/lfaoro/1476e1e14a76fd8fa6bbbf3a164dd0cf#file-creditcard-go-L7
need it to replace all non-number characters instead of just failing
https://gist.github.com/lfaoro/1476e1e14a76fd8fa6bbbf3a164dd0cf#file-creditcard-go-L7
need it to verify the number is a valid credit card
https://gist.github.com/lfaoro/1476e1e14a76fd8fa6bbbf3a164dd0cf#file-creditcard-go-L19
could be avoided as we have the IsCreditCard step doing that already, although if we want the Luhn function to be used standalone for other types of PANs we need it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment