Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

CNPJ and CPF Validation

Title: CNPJ and CPF Validation Question: How to validade CNPJ or CPF. Answer: In Brazil every people has a ID called CPF(Cadastro de pessoa fsica) and every company has a ID called CNPJ(Cadastro nacional de pessoa jurdica). Some times we need to validate those IDs. Ps.: This function uses a function from JCL(StrKeepChars), this functions just remove other chars than numbers. ! UPDATED ! function CheckCNPJ (Numero: String): Boolean; var i, j, k, Soma, Digito: integer; IsCNPJ: Boolean; NumeroVerifica: String; begin Numero := StrKeepChars(Numero,['0'..'9']); IsCNPJ := (Length(Numero) = 14); NumeroVerifica := Copy(Numero, 0, Length(Numero)-2); for j := 1 to 2 do begin k := 2; Soma := 0; for i := Length(NumeroVerifica) downto 1 do begin Soma := Soma + (Ord(NumeroVerifica[i])-Ord('0'))*k; Inc(k); if (k 9) and IsCNPJ then k := 2; end; Digito := 11 - Soma mod 11; if Digito = 10 then Digito := 0; NumeroVerifica := NumeroVerifica + Chr(Digito + Ord('0')); end; Result := (NumeroVerifica = Numero); end;