validate method

bool validate(
  1. String input
)

Calculates and returns the validity of the Luhn checksum of input.

Implementation

bool validate(String input) {
  final onlyDigits = input.replaceAll(RegExp(r'[^\d]'), '');
  if (onlyDigits.trim().length <= 1) return false;

  var sum = 0;
  var counter = 0;
  final zero = '0'.codeUnitAt(0);
  final nine = '9'.codeUnitAt(0);

  for (final digit in onlyDigits.split('').reversed) {
    if (_isDigit(digit)) {
      final code = digit.codeUnitAt(0);
      if (code < zero || code > nine) return false;

      if (counter % 2 == 1) {
        sum += digit == '9' ? 9 : (int.parse(digit) * 2) % 9;
      } else {
        sum += int.parse(digit);
      }

      counter++;
    }
  }

  return sum % 10 == 0;
}