Skip to content

Instantly share code, notes, and snippets.

@adrianoluis
Last active May 4, 2024 16:12
Show Gist options
  • Save adrianoluis/5043397d378ae506d87366abb0ab4e30 to your computer and use it in GitHub Desktop.
Save adrianoluis/5043397d378ae506d87366abb0ab4e30 to your computer and use it in GitHub Desktop.
Utility class to validate CPF and CNPJ document types. For CPF use isValidSsn and for CNPJ use isValidTfn. Added to repo https://github.com/adrianoluis/misc-tools
public class DocumentUtil {
// CPF
private static final int[] WEIGHT_SSN = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2};
// CNPJ
private static final int[] WEIGHT_TFN = {6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2};
private static int sum(int[] weight, char[] numbers, int length) {
if (length <= 0) return 0;
final int nIdx = length - 1;
final int wIdx = weight.length > numbers.length ? length : nIdx;
return (sum(weight, numbers, nIdx) + Character.getNumericValue(numbers[nIdx]) * weight[wIdx]);
}
private static int calculate(final String document, final int[] weight) {
final char[] numbers = document.toCharArray();
int sum = sum(weight, numbers, numbers.length);
sum = 11 - (sum % 11);
return sum > 9 ? 0 : sum;
}
private static boolean check(String tfn, int length, int[] weight) {
final String number = tfn.substring(0, length);
final int digit1 = calculate(number, weight);
final int digit2 = calculate(number + digit1, weight);
return tfn.equals(number + digit1 + digit2);
}
/**
* Valida CPF
*/
public static boolean isValidSsn(String ssn) {
if (ssn == null || !ssn.matches("\\d{11}") || ssn.matches(ssn.charAt(0) + "{11}")) return false;
return check(ssn, 9, WEIGHT_SSN);
}
/**
* Valida CNPJ
*/
public static boolean isValidTfn(String tfn) {
if (tfn == null || !tfn.matches("\\d{14}")) return false;
return check(tfn, 12, WEIGHT_TFN);
}
}
@RicardoTSilva2303
Copy link

Muito obrigado Luis, me ajudou bastante.

@piresalexsandro
Copy link

Obrigado!!!

@gogaoliveira
Copy link

top

@angelosuporte
Copy link

Obrigado

@PortelaVictor
Copy link

Obrigado Luis, ajudou bastante.

@jrsguitar
Copy link

Muito obrigado!

@Pedrolaires
Copy link

Até hoje ajudando muita gente, obrigado!

@newtonneto
Copy link

Muito obrigado

@charllysonsouza
Copy link

charllysonsouza commented Jan 22, 2022

Obrigado! Estou vindo pelo curso do Nélio da Udemy. Valeu!

@lissa-sonoda
Copy link

Muito obrigada, Luis!! Ajudou demais!!

@marland-tales
Copy link

Tks bro!

@MarcioGomes78
Copy link

Obrigado em ajudar com seu conhecimento um abraço.

@yujiyamamoto64
Copy link

Passando pra agradecer tbm!

@allanbarretogaspar
Copy link

Passando pra deixar um SUPER obrigado!!!!!!!

@wallisonlemosdev
Copy link

Me salvou!

@eymatsuda2016
Copy link

Eu também estou fazendo o curso do Prof. Nélio Alves lá na Udemy. Me ajudou e muito. Obrigado pelo código

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment