-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCPFValidator.java
More file actions
25 lines (24 loc) · 888 Bytes
/
CPFValidator.java
File metadata and controls
25 lines (24 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class CPFValidator {
public static boolean isValid(String cpf) throws ExecaoCPFVazio, ExecaoCPFNaoNumerico, ExecaoDigitoInvalido, ExecaoFormatoInvalido{
if(cpf.isEmpty() || cpf == null){
throw new ExecaoCPFVazio();
}
if (cpf.length() != 11) throw new ExecaoFormatoInvalido();
int i = 10;
int soma = 0;
int digitoVerificador = 0;
for (char c: cpf.toCharArray()) {
if (!Character.isDigit(c)) throw new ExecaoCPFNaoNumerico();
if (i >= 2) {
soma += Character.getNumericValue(c) * i;
}
if (i == 1) {
digitoVerificador = Character.getNumericValue(c);
}
i--;
}
int resto = (soma * 10) % 11;
if (resto != digitoVerificador) throw new ExecaoDigitoInvalido();
return true;
}
}