Buscar

Validar CNH (Correta!)

Código

Eu havia postado um outro código com a validação do CNH, porém aquele contém erros. Essa aqui está correta:

function TForm1.ValidaCNH(sCNH: string; lExibeMsg: boolean): boolean;
const
  String1 = '987654321';
  String2 = '123456789';
var
  i,j,Digito: shortint;
  Controle, DigitoInformado: string[2];
  StringX: string;
  Soma, Decr: smallint;
begin
  sCNH := Copy('00000000000'+Trim(sCNH),(Length(Trim(sCNH))+11)-10,11 );

  Controle := '  ';
  DigitoInformado := Copy( sCNH,10,2 );
  StringX := String1;
  Decr := 0;

  if sCNH <> '00000000000' then
  for i := 1 to 2 do
  begin
    Soma := 0;
    if i = 2 then StringX := String2;
    for j := 1 to 9 do
      Soma := Soma + ( StrToInt(sCNH[j]) * StrToIntDef(StringX[j],0) );
    Digito := Soma Mod 11;
    if Digito >= 10 then
    begin
      Digito := 0;
      if i = 1 then
        Decr := 2;
    end;
    if i = 2 then
      Digito := Digito - Decr;
    Controle[i] := IntToStr( Digito )[1];
  end;

  Result := Controle = DigitoInformado;

  if not Result and lExibeMsg then
    Application.MessageBox('Número de CNH inválido!','Atenção',mb_TaskModal + mb_IconWarning);
end;
   

Publicidade

Vote na dica




Quantidade de votos: 0 votos
Aceitação: 0%


Detalhes da dica

Categoria: Object pascal
Adicionada dia: 09/07/09
Por: Emerson Evangelista Do Nascimento
Visualizada: 8260 vezes

Planeta Delphi - Tudo sobre programação Delphi Planeta Delphi - www.planetadelphi.com.br - Todos os direitos reservados | Copyright 2001-2009