isValidCpf static method

bool isValidCpf(
  1. String cpf
)

Validates the check digits of an 11-digit CPF.

Implementation

static bool isValidCpf(String cpf) {
  if (cpf.length != 11) return false;
  if (RegExp(r'^(\d)\1{10}$').hasMatch(cpf)) return false;

  int checkDigit(int count) {
    var sum = 0;
    var weight = count + 1;
    for (var i = 0; i < count; i++) {
      sum += int.parse(cpf[i]) * weight--;
    }
    final rest = sum % 11;
    return rest < 2 ? 0 : 11 - rest;
  }

  return checkDigit(9) == int.parse(cpf[9]) &&
      checkDigit(10) == int.parse(cpf[10]);
}