isCreditCardValid method

bool isCreditCardValid()

Checks the validity of the credit/debit card number using the Luhn algorithm.

Implementation

bool isCreditCardValid() {
  int sum = 0;
  bool alternate = false;

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

    if (alternate) {
      digit *= 2;
      if (digit > 9) {
        digit = (digit % 10) + 1;
      }
    }

    sum += digit;

    alternate = !alternate;
  }

  return sum % 10 == 0;
}