Como este é meu primeiro post, vou mostrar algumas funções que são extremamente necessárias para a validação de sistemas e as vezes é meio complicado encontrá-las na NET.
Validando CPF:
(Obs: Recebe o cpf em tipo string e retorna tipo boolean.)
function verifyCpf(s: String): Boolean;
var
resto: byte;
soma: Integer;
i, dv: Byte;
f: Byte;
ok: Boolean;
begin
s := FilterNumber(s);
ok := (Length(s) = 11) and not TodosIguais(s);
if ok then
begin
f := 2;
soma := 0;
for i := 9 downto 1 do
begin
soma := soma + StrToInt(s[i]) * f;
f := f + 1;
end;
resto := soma mod 11;
if resto < 2 then
dv := 0
else
dv := 11 - resto;
ok := (dv = StrToInt(s[10]));
if ok then
begin
f := 2;
soma := 0;
for i := 10 downto 1 do
begin
soma := soma + StrToInt(s[i]) * f;
f := f + 1;
end;
resto := soma mod 11;
if resto < 2 then
dv := 0
else
dv := 11 - resto;
ok := (dv = StrToInt(s[11]));
end;
end;
VerifyCPF := ok;
end;
Validando CNPJ:
(Obs: Recebe o cnpj em tipo string e retorna tipo boolean.)
function verifyCgc(cCgc: String): Boolean;
var
lCgc: Boolean;
i, j, Soma, Digito: Integer;
Cgc1, Cgc2, Mult, Controle: String;
begin
Digito := 0;
cCgc := FilterNumber(cCgc);
if length(cCgc) = 14 then
begin
Cgc1 := Copy(cCgc, 1, 12);
Cgc2 := Copy(cCgc, 13, 2);
Mult := '543298765432';
Controle := '';
for j := 1 to 2 do
begin
Soma := 0;
for i := 1 to 12 do
begin
Soma := Soma + StrToInt(Cgc1[i]) * StrToInt(Mult[i]);
end;
if j = 2 then
Soma := Soma + (2 * Digito);
Digito := (Soma * 10) mod 11;
if Digito = 10 then
Digito := 0;
Controle := Controle + IntToStr(Digito);
Mult := '654329876543';
end;
if (cCgc <> '') and (Controle <> Cgc2) then
lCgc := False
else
lCgc := True;
end
else
lCGC := False;
Result := lCgc and (Not TodosIguais(cCGC));
end;
Verifica se os caracteres são iguais (função utilizada pelo CPF e CNPJ):
(Obs: Recebe uma string e retorna um boolean.)
Function TodosIguais(s: String):Boolean;
var
i : Byte;
igual : Boolean;
begin
igual := True;
i := 2;
while igual and (i <= length(s)) do begin
igual := (s[i] = s[1]);
i := i + 1;
end;
TodosIguais := igual;
End;
Removendo todos caracteres diferentes de números:
(Obs: Recebe uma string e retorna uma string sem números entre as palavras.)
function filterNumber(pSValor: String): String;
const
SC_NUM: TSetChar = ['0','1','2','3','4','5','6','7','8','9'];
var
vII: byte;
vSNew: String;
begin
vSNew := '';
for vII := 1 to length(pSValor) do
if pSValor[vII] in SC_NUM then
vSNew := vSNew + pSValor[vII];
filterNumber := vSNew;
end;
Removendo todos espaços em branco de uma string:
(Obs: Recebe uma string e retorna uma string sem espaços entre as palavras.)
function allTrim(pSStr: String): String;
var
vSCopy: String;
vII: Integer;
begin
vSCopy := '';
for vII := 1 to Length(pSStr) do
begin
if pSStr[vII] <> '' then
vSCopy := vSCopy + pSStr[vII];
end;
Result := vSCopy;
end;
Espero que gostem e utilizem as funções.
Qualquer dúvida, problema e/ou sugestão estou a disposição.
Adriano Dias da Silva