isCreditCard function
check if the string is a credit card
Implementation
bool isCreditCard(String str) {
String sanitized = str.replaceAll(new RegExp(r'[^0-9]+'), '');
if (!_creditCard.hasMatch(sanitized)) {
return false;
}
// Luhn algorithm
int sum = 0;
String digit;
bool shouldDouble = false;
for (int i = sanitized.length - 1; i >= 0; i--) {
digit = sanitized.substring(i, (i + 1));
int tmpNum = int.parse(digit);
if (shouldDouble == true) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += ((tmpNum % 10) + 1);
} else {
sum += tmpNum;
}
} else {
sum += tmpNum;
}
shouldDouble = !shouldDouble;
}
return (sum % 10 == 0);
}