creditCardNumberValidator static method

String? creditCardNumberValidator(
  1. String number
)

Implementation

static String? creditCardNumberValidator(String number) {
  // Remove any non-digits from the number.
  number = number.replaceAll(RegExp(r'[^0-9]'), '');

  // Check if the number is the correct length.
  if (number.length < 13 || number.length > 19) {
    return 'Invalid card number';
  }

  // Calculate the checksum.
  int checksum = 0;
  for (int i = 0; i < number.length; i++) {
    int digit = int.parse(number[i]);
    if (i % 2 == 0) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }
    checksum += digit;
  }

  // The checksum should be a multiple of 10.
  return checksum % 10 == 0 ? null : 'Invalid card number';
}