[Script] CPF / CNPJ - Validando um documento informado pelo usuário


Reputação 6

Olá Blippers! 💙🤖


Encontrar APIs para validar gratuitamente um CPF ou CNPJ é muito, muito difícil. Há 84 anos (hahaha!), conhecia uma API que era gratuita e tinha certa assertividade e confiabilidade para consultar CPF / CPPJ, não apenas validando se era um documento válido como também trazendo dados dos usuários (exigia um cadastro para utilização, mas se foi há algum tempo)


Uma alternativa para garantir se um CPF ou CNPJ é válido é a utilização de scripts (e que estão aos montes na rede). Abaixo, estou compartilhando que tenho utilizado em implementações, com a finalidade de garantir que o valor informado pelo usuário tem o padrão do CPF e CNPJ (para quem tem curiosidade de entender o que significa cada número do CPF) 👇


/* [ ! ] Attention¹: this script does not check the referring data of the individual or legal entity linked to the CPF and CNPJ, respectively. 
It only checks if the number sequence entered corresponds to a valid CPF or CNPJ entry standard. If you want to obtain such data,
only through HTTP Request to an API (free or paid). We do not provide an API for these cases.*/

/* [ ! ] Attention²: To use this script, the CPF and CNPJ must be entered with standard CPF or CNPJ numbers and septers.
Change if necessary and be careful about changes.
Examples: CPF --> 825.332.050-79 | CNPJ --> 98.976.100/0001-52 */

function run(input_user) {

/* here it checks if the user's input is a valid CPF */
if (input_user.length == 14) {
var cpf = input_user.trim();

cpf = cpf.replace(/\./g, '');
cpf = cpf.replace('-', '');
cpf = cpf.split('');

var v1 = 0;
var v2 = 0;
var aux = false;

for (var i = 1; cpf.length > i; i++) {
if (cpf[i - 1] != cpf[i]) {
aux = true;
}
}

if (aux == false) {
return false;
}

for (var i = 0, p = 10; (cpf.length - 2) > i; i++, p--) {
v1 += cpf[i] * p;
}

v1 = ((v1 * 10) % 11);

if (v1 == 10) {
v1 = 0;
}

if (v1 != cpf[9]) {
return false;
}

for (var i = 0, p = 11; (cpf.length - 1) > i; i++, p--) {
v2 += cpf[i] * p;
}

v2 = ((v2 * 10) % 11);

if (v2 == 10) {
v2 = 0;
}

if (v2 != cpf[10]) {
return false;
} else {
return true;
}
}

/* here it checks if the user input is a valid CNPJ */
else if (input_user.length == 18) {
var cnpj = input_user.trim();

cnpj = cnpj.replace(/\./g, '');
cnpj = cnpj.replace('-', '');
cnpj = cnpj.replace('/', '');
cnpj = cnpj.split('');

var v1 = 0;
var v2 = 0;
var aux = false;

for (var i = 1; cnpj.length > i; i++) {
if (cnpj[i - 1] != cnpj[i]) {
aux = true;
}
}

if (aux == false) {
return false;
}

for (var i = 0, p1 = 5, p2 = 13; (cnpj.length - 2) > i; i++, p1--, p2--) {
if (p1 >= 2) {
v1 += cnpj[i] * p1;
} else {
v1 += cnpj[i] * p2;
}
}

v1 = (v1 % 11);

if (v1 < 2) {
v1 = 0;
} else {
v1 = (11 - v1);
}

if (v1 != cnpj[12]) {
return false;
}

for (var i = 0, p1 = 6, p2 = 14; (cnpj.length - 1) > i; i++, p1--, p2--) {
if (p1 >= 2) {
v2 += cnpj[i] * p1;
} else {
v2 += cnpj[i] * p2;
}
}

v2 = (v2 % 11);

if (v2 < 2) {
v2 = 0;
} else {
v2 = (11 - v2);
}

if (v2 != cnpj[13]) {
return false;
} else {
return true;
}
}

/* here it returns false if the entry is different in length from 11 digits (CPF) and 18 digits (CNPJ)*/
else {
return false;
}
}

1 comentário

Reputação 4
Crachá

👏🏿

Comente