Author: Tercio Ferdinando Gaudencio Filho
How to validade CNPJ or CPF
Answer:
In Brazil every people has a ID called CPF(Cadastro de pessoa fisica) and every
company has a ID called CNPJ(Cadastro nacional de pessoa juridica). Some times we
need to validate those IDs.
1 //Validade CPF2 3 function ChkCPF(const cCPF: string): boolean;
4 function LimpaString(const StrNumerica: string): string;
5 var6 i: integer;
7 valor: string;
8 begin9 valor := StrNumerica;
10 for i := 1 to length(valor) do11 ifnot (valor[i] in ['0'..'9']) then12 Delete(valor, i, 1);
13 LimpaString := valor;
14 end;
15 16 function CharToInt(cNum: char): integer;
17 begin18 CharToInt := Ord(cNum) - 48;
19 end;
20 21 function DigiSum(N: integer): integer;
22 var23 value: integer;
24 begin25 value := N mod 10 + N div 10;
26 if value >= 10 then27 value := DigiSum(value);
28 DigiSum := value;
29 end;
30 var31 i, soma, multiplo: integer;
32 CPF: string;
33 begin34 ChkCPF := false;
35 CPF := LimpaString(cCPF);
36 if Length(CPF) <> 11 then37 exit;
38 soma := 0;
39 for i := 9 downto 1 do40 begin41 soma := soma + CharToInt(CPF[i]) * (11 - i);
42 end;
43 multiplo := soma mod 11;
44 if multiplo <= 1 then45 multiplo := 0
46 else47 multiplo := 11 - multiplo;
48 if (multiplo <> CharToInt(CPF[10])) then49 exit;
50 soma := 0;
51 for i := 10 downto 1 do52 begin53 soma := soma + CharToInt(CPF[i]) * (12 - i);
54 end;
55 multiplo := soma mod 11;
56 if multiplo <= 1 then57 multiplo := 11;
58 ChkCPF := CharToInt(CPF[11]) = (11 - multiplo);
59 end;
60 61 //Validade CNPJ62 63 function ChkCNPJ(const cCNPJ: string): boolean;
64 function LimpaString(const StrNumerica: string): string;
65 var66 i: integer;
67 valor: string;
68 begin69 valor := StrNumerica;
70 for i := 1 to length(valor) do71 ifnot (valor[i] in ['0'..'9']) then72 Delete(valor, i, 1);
73 LimpaString := valor;
74 end;
75 76 function CharToInt(cNum: char): integer;
77 begin78 CharToInt := Ord(cNum) - 48;
79 end;
80 81 function DigiSum(N: integer): integer;
82 var83 value: integer;
84 begin85 value := N mod 10 + N div 10;
86 if value >= 10 then87 value := DigiSum(value);
88 DigiSum := value;
89 end;
90 var91 i, soma, mult: integer;
92 CGC: string;
93 begin94 ChkCNPJ := false;
95 CGC := LimpaString(cCNPJ);
96 if Length(CGC) <> 14 then97 exit;
98 soma := 0;
99 mult := 2;
100 for i := 12 downto 1 do101 begin102 soma := soma + CharToInt(CGC[i]) * mult;
103 mult := mult + 1;
104 if mult > 9 then105 mult := 2;
106 end;
107 mult := soma mod 11;
108 if mult <= 1 then109 mult := 0
110 else111 mult := 11 - mult;
112 if mult <> CharToInt(CGC[13]) then113 exit;
114 soma := 0;
115 mult := 2;
116 for i := 13 downto 1 do117 begin118 soma := soma + CharToInt(CGC[i]) * mult;
119 mult := mult + 1;
120 if mult > 9 then121 mult := 2;
122 end;
123 mult := soma mod 11;
124 if mult <= 1 then125 mult := 0
126 else127 mult := 11 - mult;
128 ChkCNPJ := mult = CharToInt(CGC[14]);
129 end;