public function BrazilianIdsService::validateCpf in Brazilian IDs 8
Validates CPF numbers.
Parameters
string $value: The value of the CPF number to be validated.
array $error: If provided, it is filled with the error message at $error['message'] if any.
Return value
bool Returns TRUE if the CPF number is valid. Otherwise, returns FALSE.
Overrides BrazilianIdsServiceInterface::validateCpf
1 call to BrazilianIdsService::validateCpf()
- BrazilianIdsService::validateCpfCnpj in src/
BrazilianIdsService.php - Validates CPF or CNPJ numbers depending on the number of digits.
File
- src/
BrazilianIdsService.php, line 24
Class
- BrazilianIdsService
- Provides validation functionalities for Brazilian IDs numbers.
Namespace
Drupal\brazilian_idsCode
public function validateCpf($value, array &$error = []) {
$is_valid = FALSE;
if (isset($value) && $value !== '') {
$forbidden = array(
'00000000000',
'11111111111',
'22222222222',
'33333333333',
'44444444444',
'55555555555',
'66666666666',
'77777777777',
'88888888888',
'99999999999',
);
// Checks if the value has the correct number of digits and is none of
// the forbidden values.
if (!preg_match('/^[0-9]{11}$/', $value)) {
$error['message'] = $this
->t('CPF must be a 11-digit number.');
}
elseif (in_array($value, $forbidden)) {
$error['message'] = $this
->t('CPF cannot be a sequence of the same digit only.');
}
else {
// Checks the verification digits.
$valid_number = substr($value, 0, 9);
for ($computed_digits = 0; $computed_digits < 2; $computed_digits++) {
$sum = 0;
$n = 11 + $computed_digits;
for ($i = 0; $i < 9 + $computed_digits; $i++) {
$sum += --$n * substr($valid_number, $i, 1);
}
$reminder = $sum % 11;
$valid_number .= $reminder < 2 ? 0 : 11 - $reminder;
}
if (!($is_valid = $valid_number == $value)) {
$error['message'] = $this
->t('The number %value is not a valid CPF number.', [
'%value' => $value,
]);
}
}
}
return $is_valid;
}