You are here

public function BrazilianIdsService::validateCpfCnpj in Brazilian IDs 8

Validates CPF or CNPJ numbers depending on the number of digits.

Parameters

string $value: The value of the CPF or CNPJ 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 or CNPJ number is valid. Otherwise, returns FALSE.

Overrides BrazilianIdsServiceInterface::validateCpfCnpj

File

src/BrazilianIdsService.php, line 125

Class

BrazilianIdsService
Provides validation functionalities for Brazilian IDs numbers.

Namespace

Drupal\brazilian_ids

Code

public function validateCpfCnpj($value, array &$error = []) {
  $is_valid = FALSE;
  if (isset($value) && $value !== '') {

    // Validates as CPF or CNPJ depending on the number of digits.
    if (preg_match('/^[0-9]{11}$/', $value)) {

      // CPF number.
      $is_valid = $this
        ->validateCpf($value, $error);
    }
    elseif (preg_match('/^[0-9]{14}$/', $value)) {

      // CNPJ number.
      $is_valid = $this
        ->validateCnpj($value, $error);
    }
    else {

      // Value does not match any of the allowed formats.
      $error['message'] = $this
        ->t('The number %value does not match a CPF or a CNPJ number.', [
        '%value' => $value,
      ]);
    }
  }
  return $is_valid;
}