validCPF static method

String? Function() validCPF(
  1. String value, {
  2. String? errorMessage,
})

Returns a validation function that checks if the input value is a valid CPF (Brazilian individual taxpayer registry).

The validation function will return an error message if the value does not meet the CPF format or fails the CPF check, otherwise it returns null indicating the value is valid.

value: The input value to validate. errorMessage: The error message to display if the validation fails. If not provided, a default message is used.

Implementation

static String? Function() validCPF(
  String value, {
  String? errorMessage,
}) {
  return () {
    String cpf = value.replaceAll(RegExp(r'\D'), '');

    if (cpf.length != 11 || RegExp(r'^\d{11}$').hasMatch(cpf)) {
      return errorMessage ?? 'Please enter a valid CPF.';
    }

    int sum1 = 0;
    for (int i = 0; i < 9; i++) {
      sum1 += int.parse(cpf[i]) * (10 - i);
    }
    int digit1 = (sum1 * 10) % 11;
    if (digit1 == 10) digit1 = 0;

    int sum2 = 0;
    for (int i = 0; i < 10; i++) {
      sum2 += int.parse(cpf[i]) * (11 - i);
    }
    int digit2 = (sum2 * 10) % 11;
    if (digit2 == 10) digit2 = 0;

    if (digit1 != int.parse(cpf[9]) || digit2 != int.parse(cpf[10])) {
      return errorMessage ?? 'Please enter a valid CPF.';
    }

    return null;
  };
}