Docs
Checking Raims account
Integrations

CPF and CNPJ validation

Validate the format and check digits before sending tax_id and learn how to handle INVALID_TAXID.

Before calling the Raims API with tax_id, your integration must validate the CPF or CNPJ format and check digits in your own system.

Run this check as your customer enters the document number so you can show what needs correcting in the field itself. This avoids requests with an invalid tax_id and validation errors in the application consuming our API, improving the experience for your end customers.

The tax_id field accepts CPF, numeric CNPJ, and alphanumeric CNPJ. Validation checks the format and the two check digits, which are calculated from the preceding characters.

In API responses, tax_id_type identifies the document returned in tax_id: cpf for CPF and cnpj for CNPJ, whether numeric or alphanumeric.

Before sending tax_id

Complete these steps in your system before sending the request to Raims servers:

From the entered document to the request
  1. Receive the document

    Read it as text. Preserve leading zeros and letters in alphanumeric CNPJ.

  2. Normalize and validate

    Normalize formatting and check length, characters, and check digits in the backend.

  3. Valid:

    Send to the API

    Send tax_id as a JSON string and handle the API response, which also validates the document.

  4. Invalid:

    Request a correction

    Highlight the field and keep the entered value. Ask for a correction before sending, without replacing the digits.

Form validation does not replace validation in the integration backend.

Use a message such as "Check the CPF or CNPJ you entered". Keep the entered value so your customer can correct it. The integration must send the document provided by the customer, without replacing its check digits with others that make the calculation pass.

JavaScript example

The JavaScript code is a reference for implementing validation in your integration's language. Apply the same rules in the backend and, when there is a form, also in the interface to guide users as they enter the data.

In this example, the function returns the normalized document when it is valid, or null when it needs correcting. It accepts CPF, numeric CNPJ, and alphanumeric CNPJ.

validacao-cpf-cnpj.js
function normalizeAndValidateTaxId(value) {
  if (typeof value !== 'string') return null;

  const input = value.replace(/[\p{White_Space}./-]/gu, '');
  if (!/^[0-9A-Za-z]+$/.test(input)) return null;

  const taxId = input.toUpperCase();
  const isCpf = /^[0-9]{11}$/.test(taxId);
  const isCnpj = /^[0-9A-Z]{12}[0-9]{2}$/.test(taxId);
  if (!isCpf && !isCnpj) return null;
  if (isCpf && /^([0-9])\1{10}$/.test(taxId)) return null;

  const base = taxId.slice(0, -2);
  if (isCnpj && base === '000000000000') return null;

  const weights = isCpf
    ? [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
    : [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
  const first = calculateCheckDigit(base, weights.slice(1));
  const second = calculateCheckDigit(`${base}${first}`, weights);

  return taxId.endsWith(`${first}${second}`) ? taxId : null;
}

function calculateCheckDigit(base, weights) {
  const sum = [...base].reduce(
    (total, character, index) =>
      total + (character.charCodeAt(0) - 48) * weights[index],
    0,
  );
  const remainder = sum % 11;
  return remainder < 2 ? 0 : 11 - remainder;
}

// Documento ilustrativo usado no manual de cálculo da Receita Federal.
const taxId = normalizeAndValidateTaxId('12.abc.345/01de-35');
if (taxId === null) {
  throw new Error('Confira o CPF ou CNPJ informado');
}

const body = { tax_id: taxId }; // { tax_id: '12ABC34501DE35' }
// Acrescente os demais campos exigidos pelo endpoint antes de enviar.

For a CPF such as 123.456.789-09, the function returns 12345678909. Inputs such as 00000000000, 12ABC34501DE34, or a value received as a number return null. Handle this result in the form or backend flow before building the request.

Normalize the document

Remove spaces, periods (.), slashes (/), and hyphens (-), and convert letters to uppercase. Raims accepts this formatting and applies normalization before checking the document.

Illustrative inputNormalized value
123.456.789-0912345678909
12.abc.345/01de-3512ABC34501DE35

Keep the document as text at every step. Converting it to a number removes leading zeros; extracting only numbers removes the letters from an alphanumeric CNPJ. Characters outside the allowed sets must produce a validation message rather than being silently removed.

Numeric CNPJs remain valid and coexist with the alphanumeric format. Prepare fields, masks, and libraries for both, as described in the Receita Federal questions and answers about alphanumeric CNPJ.

How to validate a CPF

After normalization, a CPF must have exactly 11 characters, all from 0 to 9. Raims rejects sequences with the same repeated digit, such as 00000000000 and 11111111111.

The first nine digits form the base; the last two are check digits. Calculate each check digit using modulo 11:

  1. Multiply the nine base digits, from left to right, by the weights 10, 9, 8, 7, 6, 5, 4, 3, 2 and add the products.
  2. Find the remainder when dividing the sum by 11. If it is 0 or 1, the check digit is 0; otherwise, it is 11 - remainder.
  3. Append the first calculated check digit to the base. Repeat with the weights 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 to obtain the second.
  4. Compare the two results with the last two digits received.

The procedure is documented in the National Treasury GRU collection protocol, section IV.

In the illustrative example 12345678909, the first sum is 210, with remainder 1, producing 0. The second sum is 255, with remainder 2, producing 9. The calculated check digits match 09.

How to validate a CNPJ

After normalization, check these conditions:

PartFormat
First 12 charactersNumbers from 0 to 9 or letters from A to Z.
Last 2 charactersNumbers from 0 to 9 only, which are the check digits.
TotalExactly 14 characters.

Raims also rejects a CNPJ whose 12 base characters are all zero, including 00000000000000. The calculation is the same for numeric and alphanumeric CNPJ:

  1. Convert each base character to ASCII code - 48. Numbers keep their value; A is 17, B is 18, and Z is 42.
  2. Multiply the 12 values by the weights 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 and add the products.
  3. Divide the sum by 11. A remainder of 0 or 1 produces check digit 0; otherwise, use 11 - remainder.
  4. Append the first check digit and repeat with the weights 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2.
  5. Compare the two calculated check digits with those received.

The check digit calculation manual published by Receita Federal uses 12ABC34501DE35: the sums 459 and 424 produce check digits 3 and 5. This is a calculation example and does not identify a Raims customer.

How to handle INVALID_TAXID

When the API returns HTTP 400 with error.code equal to INVALID_FIELDS, look for the item with field: "tax_id" and code: "INVALID_TAXID" in error.details.

This detail means the provided value did not pass CPF or CNPJ validation. Check its length after normalization, allowed characters, and both check digits. A CPF with all identical digits or a CNPJ with all 12 base characters equal to zero is also rejected.

Code in error.details for tax_idWhat to correct
REQUIREDEnter the document. The field is missing, null, or empty after normalization.
INVALID_TYPESend a quoted JSON string instead of a number, object, or another incompatible type.
INVALID_TAXIDCorrect the format or check digits of the document provided.

Associate the error with the CPF/CNPJ field in your system's interface and keep the other entered data. Ask for a correction before trying again; resending the same invalid value does not resolve the issue. The API continues validating the document in every request, even if your application has already checked it.

See the endpoint reference for the request fields and requirements, and HTTP response codes for the general error format.

What this validation confirms

Passing the calculation confirms only that the format and check digits are consistent. It does not prove that a registration exists, that its status is regular, or that the document belongs to the person providing it. The examples in this guide explain the calculation; do not use them as real customer documents.

When your flow requires registration or identity verification, perform the corresponding check. See the official Receita Federal services for CPF registration status and CNPJ lookup.