isValidCIF static method

bool isValidCIF(
  1. String cif
)

Validates CIF with checksum algorithm

Implementation

static bool isValidCIF(String cif) {
  if (cif.length != 9) return false;
  final type = cif[0].toUpperCase();
  if (!'ABCDEFGHJNPQRSUVW'.contains(type)) return false;

  final digits = cif.substring(1, 8);
  if (int.tryParse(digits) == null) return false;

  // Checksum calculation (specific algorithm)
  int sum = 0;
  for (int i = 0; i < digits.length; i++) {
    int digit = int.parse(digits[i]);
    if (i % 2 == 0) {
      digit *= 2;
      digit = digit ~/ 10 + digit % 10;
    }
    sum += digit;
  }
  final control = (10 - (sum % 10)) % 10;

  final lastChar = cif[8];
  // Can be letter or digit depending on type
  if ('NPQRSW'.contains(type)) {
    return lastChar == 'JABCDEFGHI'[control];
  } else {
    return lastChar == control.toString() ||
        lastChar == 'JABCDEFGHI'[control];
  }
}