2005. augusztus 27., szombat

CNPJ and CPF Validation


Problem/Question/Abstract:

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.

//Validade CPF

function ChkCPF(const cCPF: string): boolean;
  function LimpaString(const StrNumerica: string): string;
  var
    i: integer;
    valor: string;
  begin
    valor := StrNumerica;
    for i := 1 to length(valor) do
      if not (valor[i] in ['0'..'9']) then
        Delete(valor, i, 1);
    LimpaString := valor;
  end;

  function CharToInt(cNum: char): integer;
  begin
    CharToInt := Ord(cNum) - 48;
  end;

  function DigiSum(N: integer): integer;
  var
    value: integer;
  begin
    value := N mod 10 + N div 10;
    if value >= 10 then
      value := DigiSum(value);
    DigiSum := value;
  end;
var
  i, soma, multiplo: integer;
  CPF: string;
begin
  ChkCPF := false;
  CPF := LimpaString(cCPF);
  if Length(CPF) <> 11 then
    exit;
  soma := 0;
  for i := 9 downto 1 do
  begin
    soma := soma + CharToInt(CPF[i]) * (11 - i);
  end;
  multiplo := soma mod 11;
  if multiplo <= 1 then
    multiplo := 0
  else
    multiplo := 11 - multiplo;
  if (multiplo <> CharToInt(CPF[10])) then
    exit;
  soma := 0;
  for i := 10 downto 1 do
  begin
    soma := soma + CharToInt(CPF[i]) * (12 - i);
  end;
  multiplo := soma mod 11;
  if multiplo <= 1 then
    multiplo := 11;
  ChkCPF := CharToInt(CPF[11]) = (11 - multiplo);
end;

//Validade CNPJ

function ChkCNPJ(const cCNPJ: string): boolean;
  function LimpaString(const StrNumerica: string): string;
  var
    i: integer;
    valor: string;
  begin
    valor := StrNumerica;
    for i := 1 to length(valor) do
      if not (valor[i] in ['0'..'9']) then
        Delete(valor, i, 1);
    LimpaString := valor;
  end;

  function CharToInt(cNum: char): integer;
  begin
    CharToInt := Ord(cNum) - 48;
  end;

  function DigiSum(N: integer): integer;
  var
    value: integer;
  begin
    value := N mod 10 + N div 10;
    if value >= 10 then
      value := DigiSum(value);
    DigiSum := value;
  end;
var
  i, soma, mult: integer;
  CGC: string;
begin
  ChkCNPJ := false;
  CGC := LimpaString(cCNPJ);
  if Length(CGC) <> 14 then
    exit;
  soma := 0;
  mult := 2;
  for i := 12 downto 1 do
  begin
    soma := soma + CharToInt(CGC[i]) * mult;
    mult := mult + 1;
    if mult > 9 then
      mult := 2;
  end;
  mult := soma mod 11;
  if mult <= 1 then
    mult := 0
  else
    mult := 11 - mult;
  if mult <> CharToInt(CGC[13]) then
    exit;
  soma := 0;
  mult := 2;
  for i := 13 downto 1 do
  begin
    soma := soma + CharToInt(CGC[i]) * mult;
    mult := mult + 1;
    if mult > 9 then
      mult := 2;
  end;
  mult := soma mod 11;
  if mult <= 1 then
    mult := 0
  else
    mult := 11 - mult;
  ChkCNPJ := mult = CharToInt(CGC[14]);
end;

Nincsenek megjegyzések:

Megjegyzés küldése