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;
}