import static java.lang.Integer.parseInt
def boolean validateCPF_CNPJ(String cpf_cnpj) {
// Strip non-numeric chars
cpf_cnpj = cpf_cnpj.replaceAll("[^0-9]", "")
// Obvious checks: needs to be 11 digits, and not all be the same digit
if (cpf_cnpj.length() != 11 || cpf_cnpj.toSet().size() == 1) {
//return false
}
else {
int add = 0
// Check for verifier digit 1
for (int i = 0; i < 9; i++) add += parseInt(cpf_cnpj) * (10 - i)
int rev = 11 - (add % 11)
if (rev == 10 || rev == 11) rev = 0
if (rev != parseInt(cpf_cnpj[9])) return false
add = 0;
// Check for verifier digit 2
for (int i = 0; i < 10; i++) add += parseInt(cpf_cnpj) * (11 - i)
rev = 11 - (add % 11)
if (rev == 10 || rev == 11) rev = 0
if (rev != parseInt(cpf_cnpj[10])) return false
return true
}
// Obvious checks: needs to be 14 digits, and not all be the same digit
if (cpf_cnpj.length() != 14 || cpf_cnpj.toSet().size() == 1) {
return false
}
else {
String cnpj = cpf_cnpj
int tamanho = cnpj.length() - 2
String numeros = cnpj.substring(0,tamanho)
String digitos = cnpj.substring(tamanho)
int soma = 0
int pos = tamanho - 7
// if (parseInt(numeros[0]) == 2)
for (i = tamanho; i >= 1; i--)
{
soma += parseInt(numeros[tamanho - i]) * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != parseInt(digitos[0]))
return false;
tamanho = tamanho + 1;
numeros = cnpj.substring(0,tamanho);
soma = 0;
pos = tamanho - 7;
for (i = tamanho; i >= 1; i--)
{
soma += parseInt(numeros[tamanho - i]) * pos--;
if (pos < 2)
pos = 9;
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if (resultado != parseInt(digitos[1]))
return false;
return true
}
}
return validateCPF_CNPJ(value)
Script to Validade both CPF and CNPJ (Brazil)
Moderators: hugo, alexandre, rmvanarkel
-
- Posts: 16
- Joined: Fri Nov 17, 2017 2:24 pm