You are here

function br_tax_number_cnpj_validator in Brazilian IDs 7

Function to validate if value is a cnpj

Parameters

string $value:

Return value

array TRUE or FALSE and MSG error

1 call to br_tax_number_cnpj_validator()
br_tax_number_fields_cnpj_validate in ./br_tax_number_fields.module
Validation callback.

File

./br_tax_number_fields.module, line 143
Adds Brazilian Tax Number field widgets to text field type at the Field UI and creates new form element types for use in the Form API.

Code

function br_tax_number_cnpj_validator($value) {
  if (!empty($value)) {
    $forbidden = array(
      '00000000000000',
      '11111111111111',
      '22222222222222',
      '33333333333333',
      '44444444444444',
      '55555555555555',
      '66666666666666',
      '77777777777777',
      '88888888888888',
      '99999999999999',
    );
    if (in_array($value, $forbidden)) {
      return array(
        'status' => FALSE,
        'msg' => t('CNPJ field does not allow a sequence of the same number.'),
      );
    }
    if (strlen($value) != 14) {
      return array(
        'status' => FALSE,
        'msg' => t('CNPJ must have 14 digits.'),
      );
    }
    else {

      //@TODO - Translate variables to english
      $cnpj = $value;
      $k = 6;
      $soma1 = 0;
      $soma2 = 0;
      for ($i = 0; $i < 13; $i++) {
        $k = $k == 1 ? 9 : $k;
        $soma2 += $cnpj[$i] * $k;
        $k--;
        if ($i < 12) {
          if ($k == 1) {
            $k = 9;
            $soma1 += $cnpj[$i] * $k;
            $k = 1;
          }
          else {
            $soma1 += $cnpj[$i] * $k;
          }
        }
      }
      $digito1 = $soma1 % 11 < 2 ? 0 : 11 - $soma1 % 11;
      $digito2 = $soma2 % 11 < 2 ? 0 : 11 - $soma2 % 11;
      if ($cnpj[12] != $digito1 && $cnpj[13] != $digito2) {
        return array(
          'status' => FALSE,
          'msg' => t('CNPJ number you have entered is invalid.'),
        );
      }
    }
  }
  return array(
    'status' => TRUE,
  );
}