Olá comunidade,
Hoje resolvi disponibilizar um algoritmo para a validação de CNH, essa função já contempla os dois modelos de CNH. Aproveitem!
function ValidaCNH(cnh: string): Boolean; function valida_new_cnh(cnh: String): Boolean; var Soma, Conta, Dv, Digito, i: Integer; CnhN: String; NumerosIguais: Boolean; begin Result := False; NumerosIguais := True; CnhN := FormatFloat('00000000000', StrToFloat(trim(cnh))); Soma := 0; {Validando se todos o números são iguais} for i := 1 to length(CnhN) - 1 do if CnhN[1] <> CnhN[i] then NumerosIguais := False; if NumerosIguais then Exit; for i := 1 to length(CnhN) - 2 do Soma := Soma + (StrtoInt(CnhN[i]) * (i + 1)); Conta := (Soma div 11) * 11; if (Soma - Conta) < 2 then Dv := 0 else Dv := 11 - (Soma - Conta); Digito := StrToInt(CnhN[10]); if Digito = Dv then Result := True; end; function valida_old_cnh(cnh: String): Boolean; var Soma, Conta, Dv, Digito, i: Integer; CnhN: String; NumerosIguais: Boolean; begin Result := False; NumerosIguais := True;; CnhN := FormatFloat('000000000', StrToFloat(trim(cnh))); Soma := 0; {Validando se todos o números são iguais} for i := 1 to length(CnhN) - 1 do if CnhN[1] <> CnhN[i] then NumerosIguais := False; if NumerosIguais then Exit; for i := 1 to length(CnhN) - 1 do Soma := Soma + (StrtoInt(CnhN[i]) * (i + 1)); Digito := StrToInt(CnhN[9]); Conta := Soma mod 11; if Conta = 10 then Conta := 0; if Digito = Conta then result := True; end; begin result := (valida_new_cnh(cnh) or valida_old_cnh(cnh)); end;
Bom eu testei com algumas CNH’s e ela funcionou na boa, se tiverem problema me avisem.
Abraço a todos.
Deixe um comentário