You are here

function _brazilianids_validate_cnpj in Brazilian IDs 6

Check if the provided CNPJ is valid

Parameters

&$cnpj: Number, the CNPJ

$clean: Boolean, FALSE to not clear the number

Return value

Boolean, true if its a valid CNPJ

3 calls to _brazilianids_validate_cnpj()
brazilianids_field in ./brazilianids_cck.inc
Implementation of hook_field().
brazilianids_user in ./brazilianids.module
Implementation of hook_user().
_brazilianids_is_cpf_cnpj in ./brazilianids.check.inc
Return 'CPF' or 'CNPJ' depend of the type of param

File

./brazilianids.check.inc, line 107
brazilianids.check.inc

Code

function _brazilianids_validate_cnpj(&$cnpj, $clean = TRUE) {

  // Clear the CPF
  if ($clean) {
    $cnpj = _brazilianids_clean_cpfcnpj($cnpj);
  }

  // Check if its not the forbidden combinations
  if (drupal_strlen($cnpj) != 14 or $cnpj == '00000000000000' or $cnpj == '11111111111111' or $cnpj == '22222222222222' or $cnpj == '33333333333333' or $cnpj == '44444444444444' or $cnpj == '55555555555555' or $cnpj == '66666666666666' or $cnpj == '77777777777777' or $cnpj == '88888888888888' or $cnpj == '99999999999999') {
    return NULL;
  }
  else {
    $i = 0;
    while ($i < 14) {
      $cnpj_d[$i] = drupal_substr($cnpj, $i, 1);
      $i++;
    }
    $digit = $cnpj[0] * 5 + $cnpj[1] * 4 + $cnpj[2] * 3 + $cnpj[3] * 2 + $cnpj[4] * 9 + $cnpj[5] * 8 + $cnpj[6] * 7 + $cnpj[7] * 6 + $cnpj[8] * 5 + $cnpj[9] * 4 + $cnpj[10] * 3 + $cnpj[11] * 2;

    // Calculate the digit and check it
    $digit = 11 - $digit % 11;
    if ($digit == 10 or $digit == 11) {
      $digit = 0;
    }
    if ($digit != $cnpj[12]) {
      return NULL;
    }
    $digit = $cnpj[0] * 6 + $cnpj[1] * 5 + $cnpj[2] * 4 + $cnpj[3] * 3 + $cnpj[4] * 2 + $cnpj[5] * 9 + $cnpj[6] * 8 + $cnpj[7] * 7 + $cnpj[8] * 6 + $cnpj[9] * 5 + $cnpj[10] * 4 + $cnpj[11] * 3 + $digit * 2;

    // Calculate the digit and check it
    $digit = 11 - $digit % 11;
    if ($digit == 10 or $digit == 11) {
      $digit = 0;
    }
    if ($digit != $cnpj[13]) {
      return NULL;
    }
    return $cnpj;
  }
}