isCreditCard static method

bool isCreditCard(
  1. String value
)

Returns true for a valid credit card number using the Luhn algorithm.

Implementation

static bool isCreditCard(String value) {
  final String cleaned = value.replaceAll(RegExp(r'[\s-]'), '');
  if (cleaned.length < 12 || cleaned.length > 19) return false;
  if (!RegExp(r'^[0-9]+$').hasMatch(cleaned)) return false;

  int sum = 0;
  bool alternate = false;
  for (int i = cleaned.length - 1; i >= 0; i--) {
    int digit = int.parse(cleaned[i]);
    if (alternate) {
      digit *= 2;
      if (digit > 9) digit -= 9;
    }
    sum += digit;
    alternate = !alternate;
  }
  return sum % 10 == 0;
}