luhnCheck method

bool luhnCheck(
  1. String cardNumber
)

Implementation

bool luhnCheck(String cardNumber) {
  if (cardNumber.isEmpty) {
    return false;
  }

  cardNumber = cardNumber.replaceAll(RegExp(r'\s'), ''); // Remove spaces

  int sum = 0;
  bool isAlternate = false;

  for (int i = cardNumber.length - 1; i >= 0; i--) {
    int digit = int.parse(cardNumber[i]);

    if (isAlternate) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }

    sum += digit;
    isAlternate = !isAlternate;
  }

  return sum % 10 == 0;
}