validate method

  1. @override
bool validate(
  1. String cpf, {
  2. int? state,
})
override

This method checks if a given CPF is valid and returns true or false

The optional state argument refers to the location of the CPF to be generated.

Usage:

final cpf = CPFUtil();
// This will validate a given CPF (Must be a String)
print(cpf.validate('352.753.028-27')); // -> true

You can check the state of a CPF by looking at the last number before the two verifiers digits.

The state is not checked if ommited

All the information about the validation and the states number can be obtained here:

https://pt.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas

Implementation

@override
bool validate(String cpf, {int? state}) {
  if (cpf.length < 11) return false;

  cpf = cpf.replaceAll('.', '').replaceAll('-', '');

  final invalidCombinations =
      List.generate(10, (index) => '${"$index" * 11}');

  if (invalidCombinations.contains(cpf)) return false;

  var parsedCPF =
      cpf.split('').map<int>((element) => int.parse(element)).toList();

  return (state != null ? parsedCPF[8] == state : true) &&
      _calculateVerifyingDigit(parsedCPF.sublist(0, 9)) == parsedCPF[9] &&
      _calculateVerifyingDigit(parsedCPF.sublist(0, 10)) == parsedCPF[10];
}