GARANTIR DESCONTO

Fórum validar cpf #345202

28/08/2007

0

Olá pessoal como posso fazer validação de cpf?


Robinhocne

Robinhocne

Responder

Posts

28/08/2007

Romulocpd

Faça uma simples busca no historico do forum que conseguirá e qualquer coisa tem vários exemplos em www.delphi.eti.br


Responder

Gostei + 0

28/08/2007

Sergiokawahara

Amigo faz assim:

function TestCPF(Dado : String) : String;
var
D1 : array[1..9] of Byte;
I,DF1,DF2,DF3,DF4,DF5,DF6,Resto1,Resto2,PrimeiroDigito,SegundoDigito : integer;
vCpf : String[11];
begin
Result := ´0´;
vCpf := ´´;

if length(Dado) > 11 then
begin
for i := 1 to length(Dado) do
if Dado[i] in [´0´..´9´] then
vCpf := vCpf + Dado[i];
Dado := vCpf;
end;

if Length(Dado) = 11 then
begin
for I := 1 to 9 do
if Dado[I] in [´0´..´9´] then
D1[I] := StrToInt(Dado[I])
else
Result := ´´;

if Result <> ´´ then
begin
DF1 := 0;
DF2 := 0;
DF3 := 0;
DF4 := 0;
DF5 := 0;
DF6 := 0;
Resto1 := 0;
Resto2 := 0;
PrimeiroDigito := 0;
SegundoDigito := 0;
DF1 := 10*D1[1] + 9*D1[2] + 8*D1[3] + 7*D1[4] + 6*D1[5] + 5*D1[6] +
4*D1[7] + 3*D1[8] + 2*D1[9];
DF2 := DF1 div 11;
DF3 := DF2 * 11;
Resto1 := DF1 - DF3;
if (Resto1 = 0) or (Resto1 = 1) then
PrimeiroDigito := 0
else
PrimeiroDigito := 11 - Resto1;
DF4 := 11*D1[1] + 10*D1[2] + 9*D1[3] + 8*D1[4] + 7*D1[5] + 6*D1[6] +
5*D1[7] + 4*D1[8] + 3*D1[9] + 2*PrimeiroDigito;
DF5 := DF4 div 11;
DF6 := DF5 * 11;
Resto2 := DF4 - DF6;
if (Resto2 = 0) or (Resto2 = 1) then
SegundoDigito := 0
else
SegundoDigito := 11 - Resto2;

if (PrimeiroDigito <> StrToInt(Dado[10])) or (SegundoDigito <> StrToInt(Dado[11])) then
begin
ShowMessage(´Atenção! CPF Invalido.´);
Result := ´F´; // cpf incorreto
end
else
begin
Dado := Copy(Dado,1,3)+´.´+Copy(Dado,4,3)+´.´+Copy(Dado,7,3)+´-´+Copy(Dado,10,2);
Result := Dado; // cpf correto
end;
end;
end
else
if Length(Dado) <> 0 then
begin
ShowMessage(´Atenção! CPF Invalido.´);
Result := ´F´; // cpf incorreto
end;

if Length(Dado) = 0 then
begin
ShowMessage(´Atenção! CPF em branco.´);
Result := ´0´; // nao foi digitado o cpf
end;
end;

como usar a função:

/ Testa o CPF e retorna com a mascara.
// ex vRetorno := TestCPF(´000000000-00´) obs qualquer jeito que quiser digitar.
// se o retorno for ´F´ deu errado.


Responder

Gostei + 0

28/08/2007

Emerson Nascimento

Eis algumas rotinas que eu publiquei no [url=http://www.delphi.eti.br]Planeta Delphi[/url]

[b:5d86d7cba2]Validar CNPJ[/b:5d86d7cba2]
Function ValidaCNPJ(sCNPJ: string; MostraMsg: boolean = true): boolean;
const String1 = ´543298765432´;
      String2 = ´654329876543´;
var i,j,Digito: byte;
     Controle: string[2];
     StringX: string;
     Soma: smallint;
begin
   sCNPJ := Copy(´00000000000000´+Trim(sCNPJ),(Length(Trim(sCNPJ))+14)-13, 14);
   Controle := ´   ´;
   Digito := 0;
   StringX := String1;
   for i := 1 to 2 do
   begin
      Soma := 0;
      if i = 2 then StringX := String2;
      for j := 1 to 12 do
          Soma := Soma + (StrToIntDef(sCNPJ[j],0) * StrToIntDef(StringX[j], 0));
      if i = 2 then
          Soma := Soma + (2 * Digito);
      Digito := (Soma * 10) Mod 11;
      if Digito = 10 then
          Digito := 0;
      Controle[i] := IntToStr(Digito)[1];
   end;
   Result := Controle = Copy(sCNPJ, 13, 2);
   if not Result and MostraMsg then
       Application.MessageBox(´Número de CNPJ inválido!´,´Atenção´,mb_TaskModal + mb_IconWarning);
end;


[b:5d86d7cba2]Validar CPF[/b:5d86d7cba2]
function ValidaCPF(sCPF: string; MostraMsg: boolean = true): boolean;
const String1 = ´100908070605040302´;
      String2 = ´111009080706050403´;
var i,j,Digito: byte;
     Controle: string[2];
     StringX: string;
     Soma: smallint;
begin
   sCPF := Copy(´00000000000´+Trim(sCPF),(Length(Trim(sCPF))+11)-10, 11);
   Controle := ´   ´;
   Digito := 0;
   StringX := String1;

   for i := 1 to 2 do
   begin
      Soma := 0;
      if i = 2 then StringX := String2;
      for j := 1 to 9 do
          Soma := Soma + (StrToIntDef(sCPF[j],0) * StrToIntDef(Copy(StringX,j+(j-1),2 ), 0));
      if i = 2 then
          Soma := Soma + (2 * Digito);
      Digito := (Soma * 10) Mod 11;
      if Digito = 10 then
          Digito := 0;
      Controle[i] := IntToStr(Digito)[1];
   end;
   Result := Controle = Copy(sCPF, 10, 2);
   if not Result and MostraMsg then
       Application.MessageBox(´Número de CPF inválido!´, ´Atenção´,mb_TaskModal + mb_IconWarning);
end;


[b:5d86d7cba2]Validar PIS[/b:5d86d7cba2]
function ValidaPIS(sPIS: string; MostraMsg: boolean = true): boolean;
var
    iSoma: integer;
    i, iDigito, iDigVer, iMult: shortint;
begin
    Result := Length(Trim(sPIS)) = 11;

    if Result then
    begin
     iDigVer := strtoint(sPIS[11]);
     iSoma := 0;
     iMult := 2;

     for i := 10 downto 1 do
     begin
      iSoma := iSoma + (iMult * strtoint(sPIS[I]));
      if iMult < 9
      then Inc(iMult)
      else iMult := 2;
     end;
     iDigito := 11 - (iSoma mod 11);

     if iDigito > 9 then iDigito := 0;
     Result := (iDigVer = iDigito);
    end;

    if not Result and MostraMsg then
       Application.MessageBox(´Número do PIS inválido!´,´Atenção´,mb_TaskModal + mb_IconWarning);
end;


[b:5d86d7cba2]Validar Título de Eleitor[/b:5d86d7cba2]
function ValidaTituloEleitor(sTitulo: string; MostraMsg: boolean = True): boolean;
const
    Multiplicadores: array[1..11] of shortint = (10,9,8,7,6,5,4,3,2,4,3);
var
    iCont, iAux, DigCalculado, DigInformado: shortint;
    iDigito: integer;
begin
    result := false;
    if Length(stitulo) = 0 then
     exit;

    stitulo := StringOfChar(´0´,13-Length(stitulo))+stitulo; // 13 posições
    iAux := StrToInt(Copy(stitulo,10,2)); // valor para auxiliar o cálculo do dígito

    // dígito verificador
    DigInformado := StrToInt(Copy(stitulo,12,2));;
    DigCalculado := 0;

    iDigito := 0;
    for iCont := 1 to 11 do
    begin
     iDigito := iDigito + (StrToInt(stitulo[iCont]) * Multiplicadores[iCont]);
     if iCont in [9,11] then
     begin
      iDigito := iDigito mod 11;
      if iDigito > 1 then
          iDigito := 11 - iDigito
      else
      begin
          if iAux <= 2 then
           iDigito := 1 - iDigito
          else
           iDigito := 0;
      end;
      if iCont = 9
      then Digcalculado := iDigito * 10
      else Digcalculado := Digcalculado + iDigito;
      iDigito := iDigito * 2;
     end;
    end;

    // verifica se o digito é verdadeiro
    Result := DigCalculado = DigInformado;

    if not Result and MostraMsg then
       Application.MessageBox(´Número do título de eleitor inválido!´,´Atenção´,mb_TaskModal + mb_IconWarning);
end;



Responder

Gostei + 0

28/08/2007

Robinhocne

Ok, mas como eu faço o resto digo, coloco oq no onexit do maskedit do cpf?


Responder

Gostei + 0

28/08/2007

Sergiokawahara

coloque no evento on-exit

if TestCPF(´000000000-00´) = ´F´ then
ShowMessage(´CPF, invalido´);


Responder

Gostei + 0

29/08/2007

Robinhocne

coloque no evento on-exit if TestCPF(´000000000-00´) = ´F´ then ShowMessage(´CPF, invalido´);


Não deu certo eu digito e não dá nada.


Responder

Gostei + 0

29/08/2007

Emerson Nascimento

no evento onExit do Edit, faça algo como:
if TestCPF(SeuObjetoEdit.Text) = ´F´ then
ShowMessage(´CPF invalido´);

por exemplo:
if TestCPF(Edit1.Text) = ´F´ then
ShowMessage(´CPF invalido´);

mas só vai funcionar ao sair do Edit. se digitar qualquer valor e continuar no edit o evento não será disparado.


Responder

Gostei + 0

29/08/2007

Robinhocne

no evento onExit do Edit, faça algo como: if TestCPF(SeuObjetoEdit.Text) = ´F´ then ShowMessage(´CPF invalido´); por exemplo: if TestCPF(Edit1.Text) = ´F´ then ShowMessage(´CPF invalido´); mas só vai funcionar ao sair do Edit. se digitar qualquer valor e continuar no edit o evento não será disparado.



function ValidaCPF(sCPF: string; MostraMsg: boolean = true): boolean;
const String1 = ´100908070605040302´;
      String2 = ´111009080706050403´;
var i,j,Digito: byte;
     Controle: string[2];
     StringX: string;
     Soma: smallint;
begin
   sCPF := Copy(´00000000000´+Trim(sCPF),(Length(Trim(sCPF))+11)-10, 11);
   Controle := ´   ´;
   Digito := 0;
   StringX := String1;

   for i := 1 to 2 do
   begin
      Soma := 0;
      if i = 2 then StringX := String2;
      for j := 1 to 9 do
          Soma := Soma + (StrToIntDef(sCPF[j],0) * StrToIntDef(Copy(StringX,j+(j-1),2 ), 0));
      if i = 2 then
          Soma := Soma + (2 * Digito);
      Digito := (Soma * 10) Mod 11;
      if Digito = 10 then
          Digito := 0;
      Controle[i] := IntToStr(Digito)[1];
   end;
   Result := Controle = Copy(sCPF, 10, 2);
   if not Result and MostraMsg then
       Application.MessageBox(´Número de CPF inválido!´, ´Atenção´,mb_TaskModal + mb_IconWarning);
end;


Emerson não deu certo, mas usando a sua função como podemos fazer.


Responder

Gostei + 0

29/08/2007

Robinhocne

[quote:b3ef07c7cc=´emerson.en´]no evento onExit do Edit, faça algo como: if TestCPF(SeuObjetoEdit.Text) = ´F´ then ShowMessage(´CPF invalido´); por exemplo: if TestCPF(Edit1.Text) = ´F´ then ShowMessage(´CPF invalido´); mas só vai funcionar ao sair do Edit. se digitar qualquer valor e continuar no edit o evento não será disparado.



function ValidaCPF(sCPF: string; MostraMsg: boolean = true): boolean;
const String1 = ´100908070605040302´;
      String2 = ´111009080706050403´;
var i,j,Digito: byte;
     Controle: string[2];
     StringX: string;
     Soma: smallint;
begin
   sCPF := Copy(´00000000000´+Trim(sCPF),(Length(Trim(sCPF))+11)-10, 11);
   Controle := ´   ´;
   Digito := 0;
   StringX := String1;

   for i := 1 to 2 do
   begin
      Soma := 0;
      if i = 2 then StringX := String2;
      for j := 1 to 9 do
          Soma := Soma + (StrToIntDef(sCPF[j],0) * StrToIntDef(Copy(StringX,j+(j-1),2 ), 0));
      if i = 2 then
          Soma := Soma + (2 * Digito);
      Digito := (Soma * 10) Mod 11;
      if Digito = 10 then
          Digito := 0;
      Controle[i] := IntToStr(Digito)[1];
   end;
   Result := Controle = Copy(sCPF, 10, 2);
   if not Result and MostraMsg then
       Application.MessageBox(´Número de CPF inválido!´, ´Atenção´,mb_TaskModal + mb_IconWarning);
end;


Emerson não deu certo, mas usando a sua função como podemos fazer.[/quote:b3ef07c7cc]


[b:b3ef07c7cc]Ok, Resolvido[/b:b3ef07c7cc]


Responder

Gostei + 0

12/09/2007

Jpauloss

no evento onExit do Edit, faça algo como: if TestCPF(SeuObjetoEdit.Text) = ´F´ then ShowMessage(´CPF invalido´); por exemplo: if TestCPF(Edit1.Text) = ´F´ then ShowMessage(´CPF invalido´); mas só vai funcionar ao sair do Edit. se digitar qualquer valor e continuar no edit o evento não será disparado.


Nesse código:
if TestCPF(Edit1.Text) = ´F´ then
ShowMessage(´CPF invalido´);

Quem é ´F´?
Tentei essa função aqui mas ta dando um erro na primeira linha: if TestCPF(Edit1.Text) = ´F´ then.

O erro é esse:
[Error] UnClientes.pas(238): Incompatible types


Que faço?


Responder

Gostei + 0

12/09/2007

Jpauloss

Ah meu código ta assim:
procedure TFrmCliente.cpfExit(Sender: TObject);
begin
 if ValidaCPF(cpf.text) = ´F´ then
 ShowMessage(´Cpf Inválido!´);
 cpf.SetFocus;
end;



Responder

Gostei + 0

12/09/2007

Jpauloss

sobe


Responder

Gostei + 0

12/09/2007

Jpauloss

Resolvi com essa função:
function EliminaDifNumero(S : string) : string;
var
  I : Integer;
begin
  for I := Length(S) downto 1 do
    if not (S[I] in [´ ´, ´0´..´9´]) then
      Delete(S, I, 1);

  Result := S;
end;

type
  TDigito = 0..9;

function CharToDig(vChar : Char) : TDigito;
begin
  Result := Ord(vChar) - 48
end;

function ChekCPF(CPF : string) : boolean;
var
  Dig1, Dig2 : integer;
  ii, Soma : integer;
begin
  Result := False;

  {analisa CPF no formato 99999999900}
  CPF := EliminaDifNumero(CPF);

  {comeca a verificacao do digito}
  if Length(CPF) = 11 then
  try
    {1° digito}
    Soma := 0;
    for ii := 1 to 9 do
      Inc(soma, CharToDig(CPF[10 - ii]) * (ii + 1));

    dig1 := 11 - (Soma mod 11);
    if Dig1 > 9 then Dig1 := 0;

    {2° digito}
    Soma := 0;
    for ii := 1 to 10 do
      Inc(Soma, CharToDig(CPF[11 - ii]) * (ii + 1));
    Dig2 := 11 - (Soma mod 11);
    if Dig2 > 9 then Dig2 := 0;

    {Checa os dois dígitos}
    if (Dig1 = CharToDig(CPF[10])) and
      (Dig2 = CharToDig(CPF[11])) then
      Result := True;
  except
  end;
end;

function ChekCNPJ(CNPJ : string) : boolean;
var
  Dig1, Dig2 : integer;
  ii, Soma : integer;
begin
  Result := False;
  {analisa CGC no formato 99999999999900}
  CNPJ := EliminaDifNumero(CNPJ);

  {começa a verificacao do digito}
  if Length(CNPJ) = 14 then
  try
    {1° digito}
    Soma := 0;
    for ii := 1 to 12 do
    begin
      if ii <5> 9 then Dig1 := 0;

    {2° digito}
    Soma := 0;
    for ii := 1 to 13 do
    begin
      if ii <6> 9 then Dig2 := 0;

    {Checa os dois dígitos}
    if (Dig1 = CharToDig(CNPJ[13])) and
      (Dig2 = CharToDig(CNPJ[14])) then
      Result := True;
  except
  end;
end;


exemplo de uso :
 if not ChekCPF(´11111111111´) then
    ShowMessage(´CPF Inválido´);


ou

 if not ChekCNPJ(´11111111111111´) then
    ShowMessage(´CNPJ Inválido´); 


[b:4f08f13fb5]Essa dica foi do gilsonnrodrigues extraída do forum activedelphi.[/b:4f08f13fb5]


Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar