validNumber method

bool validNumber(
  1. String ccNum
)

Implementation

bool validNumber(String ccNum) {
  if (!checkLuhn) {
    return true;
  }

  if (ccNum.length < 2) {
    return false;
  }

  String cNum = ccNum.replaceAll(RegExp(r'\D'), '');
  int mod = cNum.length % 2;
  int sum = 0;

  try {
    for (int pos = cNum.length - 1; pos >= 0; pos--) {
      int digit = int.parse(cNum[pos]);

      if (pos % 2 == mod) {
        digit *= 2;
        if (digit > 9) {
          digit -= 9;
        }
      }

      sum += digit;
    }

    return sum % 10 == 0;
  } on Exception {
    return false;
  }
}