DICAS

Visite a biblioteca de dicas da comunidade.

Saiba mais

ARTIGOS

Abordagens detalhadas sobre assuntos diversos.

Saiba mais

INICIANTES

Aprenda a programar de um modo simples e fácil.

Saiba mais

DOWNLOADS

Acesse os materiais exclusivos aos membros.

Saiba mais
voltar

PARA QUEM GOSTA DE DELPHI

Função para validar CPF.

Muitas vezes é necessário a validação das informações preenchidas,
o CPF é um caso comum de validação.
Abaixo segue uma função para verificar se um CPF é válido:

É necessário declarar Math e SysUtils,
em versões unicode declare System.Math e System.SysUtils.

Abaixo o código fonte da função:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
function IsValidCPF(pCPF: string): Boolean;
var
  v: array [0 .. 1] of Word;
  cpf: array [0 .. 10] of Byte;
  I: Byte;
begin
  Result := False;
 
  { Verificando se tem 11 caracteres }
  if Length(pCPF) <> 11 then
  begin
    Exit;
  end;
 
  { Conferindo se todos dígitos são iguais }
  if pCPF = StringOfChar('0', 11) then
    Exit;
 
  if pCPF = StringOfChar('1', 11) then
    Exit;
 
  if pCPF = StringOfChar('2', 11) then
    Exit;
 
  if pCPF = StringOfChar('3', 11) then
    Exit;
 
  if pCPF = StringOfChar('4', 11) then
    Exit;
 
  if pCPF = StringOfChar('5', 11) then
    Exit;
 
  if pCPF = StringOfChar('6', 11) then
    Exit;
 
  if pCPF = StringOfChar('7', 11) then
    Exit;
 
  if pCPF = StringOfChar('8', 11) then
    Exit;
 
  if pCPF = StringOfChar('9', 11) then
    Exit;
 
  try
    for I := 1 to 11 do
      cpf[I - 1] := StrToInt(pCPF[I]);
    // Nota: Calcula o primeiro dígito de verificação.
    v[0] := 10 * cpf[0] + 9 * cpf[1] + 8 * cpf[2];
    v[0] := v[0] + 7 * cpf[3] + 6 * cpf[4] + 5 * cpf[5];
    v[0] := v[0] + 4 * cpf[6] + 3 * cpf[7] + 2 * cpf[8];
    v[0] := 11 - v[0] mod 11;
    v[0] := IfThen(v[0] >= 10, 0, v[0]);
    // Nota: Calcula o segundo dígito de verificação.
    v[1] := 11 * cpf[0] + 10 * cpf[1] + 9 * cpf[2];
    v[1] := v[1] + 8 * cpf[3] + 7 * cpf[4] + 6 * cpf[5];
    v[1] := v[1] + 5 * cpf[6] + 4 * cpf[7] + 3 * cpf[8];
    v[1] := v[1] + 2 * v[0];
    v[1] := 11 - v[1] mod 11;
    v[1] := IfThen(v[1] >= 10, 0, v[1]);
    // Nota: Verdadeiro se os dígitos de verificação são os esperados.
    Result := ((v[0] = cpf[9]) and (v[1] = cpf[10]));
  except
    on E: Exception do
      Result := False;
  end;
end;
Exemplo de uso:
<pre lang="delphi" line="1">// Exemplo de uso:
procedure TForm1.Button1Click(Sender: TObject);
begin
  if IsValidCPF('76275651628') then
    ShowMessage('O CPF é válido.')
  else
    ShowMessage('O CPF não é válido.');
end;

Como alternativa pode-se citar o componente TACBrValidador que valida diversos
documentos e pertence a biblioteca do ACBr que é Open Source.

A fim de facilitar o entendimento de todos, colocamos a seguir todo o fonte de uma unit de exemplo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
unit Unit1;
 
interface
 
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
 
type
  TForm1 = class(TForm)
    Button1: TButton;
    EdtCpf: TLabeledEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
 
implementation
 
uses
  System.Math;
 
function IsValidCPF(pCPF: string): Boolean;
var
  v: array [0 .. 1] of Word;
  cpf: array [0 .. 10] of Byte;
  I: Byte;
begin
  Result := False;
 
  { Verificando se tem 11 caracteres }
  if Length(pCPF) <> 11 then
  begin
    Exit;
  end;
 
  { Conferindo se todos dígitos são iguais }
  if pCPF = StringOfChar('0', 11) then
    Exit;
 
  if pCPF = StringOfChar('1', 11) then
    Exit;
 
  if pCPF = StringOfChar('2', 11) then
    Exit;
 
  if pCPF = StringOfChar('3', 11) then
    Exit;
 
  if pCPF = StringOfChar('4', 11) then
    Exit;
 
  if pCPF = StringOfChar('5', 11) then
    Exit;
 
  if pCPF = StringOfChar('6', 11) then
    Exit;
 
  if pCPF = StringOfChar('7', 11) then
    Exit;
 
  if pCPF = StringOfChar('8', 11) then
    Exit;
 
  if pCPF = StringOfChar('9', 11) then
    Exit;
 
  try
    for I := 1 to 11 do
      cpf[I - 1] := StrToInt(pCPF[I]);
    // Nota: Calcula o primeiro dígito de verificação.
    v[0] := 10 * cpf[0] + 9 * cpf[1] + 8 * cpf[2];
    v[0] := v[0] + 7 * cpf[3] + 6 * cpf[4] + 5 * cpf[5];
    v[0] := v[0] + 4 * cpf[6] + 3 * cpf[7] + 2 * cpf[8];
    v[0] := 11 - v[0] mod 11;
    v[0] := IfThen(v[0] >= 10, 0, v[0]);
    // Nota: Calcula o segundo dígito de verificação.
    v[1] := 11 * cpf[0] + 10 * cpf[1] + 9 * cpf[2];
    v[1] := v[1] + 8 * cpf[3] + 7 * cpf[4] + 6 * cpf[5];
    v[1] := v[1] + 5 * cpf[6] + 4 * cpf[7] + 3 * cpf[8];
    v[1] := v[1] + 2 * v[0];
    v[1] := 11 - v[1] mod 11;
    v[1] := IfThen(v[1] >= 10, 0, v[1]);
    // Nota: Verdadeiro se os dígitos de verificação são os esperados.
    Result := ((v[0] = cpf[9]) and (v[1] = cpf[10]));
  except
    on E: Exception do
      Result := False;
  end;
end;
 
{$R *.dfm}
 
procedure TForm1.Button1Click(Sender: TObject);
begin
  if IsValidCPF(EdtCpf.Text) then
    ShowMessage('O CPF é válido.')
  else
    ShowMessage('O CPF não é válido.');
end;
 
end.

Dúvidas ou sugestões? Deixe o seu comentário!

Facebook Comments Box
  • InfusTec
  • 13.130 views
  • 5 comentários
  • 23 de março de 2015

Está gostando do conteúdo? Considere pagar um cafezinho para nossa equipe!

5 respostas para “Função para validar CPF.”

  1. Fernando Ito disse:

    Substitua ‘>’ por ‘>’
    v[1] := IfThen(v[1] >= 10, 0, v[1]);

  2. Rei do Delphi disse:

    como é que você posta uma coisa com erro! se não está compilando, não divulga, tenha dó! Aff

  3. Fontes atualizados e corrigida a exibição do caractere “>”.

    Agora colocamos um exemplo de toda a unit.

Deixe um comentário

Ir ao topo

© 2024 Infus Soluções em Tecnologia - Todos os Direitos Reservados