Cogiendo lo que habeis escrito, un ejemplo de trucomania, con algunas cosas que he añadido y con varias horas de trabajo he hecho un código que comprueba tanto si es un Nif, Cif o Nif Extrangero, creo que he contemplado casi todas las posiblilidades.
Lo he probado y parece que funciona bien pero siempre puede haber errores, si veis algo mal comentadlo please.
Pues nada aquí dejo el código para quien lo quiera
.
Código Delphi
[-]
function Letra(Numero: Integer): string;
begin
Result:= copy('TRWAGMYFPDXBNJZSQVHLCKET',1 + numero mod 23,1);
end;
function EsNif(NIF: String): Boolean;
var
Numero: Integer;
begin
Result:= FALSE;
if TryStrToInt(Copy(NIF,1,Length(NIF)-1),Numero) then
Result:= Uppercase(Copy(NIF,Length(NIF),1)) = Letra(Numero);
end;
function EsNumero(Num: Char): Boolean;
begin
try
StrToInt(Num);
Result:=True;
Except
result:=False;
end;
end;
function CadLimpiaCar(NIF: String): String;
begin
Result:= NIF;
while (pos(' ',NIF)>0) do
delete(NIF,pos(' ',NIF),1);
while (pos('-',NIF)>0) do
delete(NIF,pos('-',NIF),1);
while (pos('/',NIF)>0) do
delete(NIF,pos('/',NIF),1);
Result:=NIF;
end;
function ValidaCif(Cif : String) : Boolean;
var
Suma, Control : Integer;
n : Byte;
begin
Result := False;
Cif := UpperCase(Trim(Cif));
Cif := CadLimpiaCar(Cif);
if Length(Cif) = 9 then
begin
if EsNumero(Cif[1]) then
Result := EsNif(Cif)
else
if (Pos(Cif[1], 'ABCDEFGHPQSKLMX') = 0) then
Result := False
else
if Cif[1] = 'X' then
Result := EsNif('0'+Copy(Cif,2,8))
else
begin
if EsNumero(Cif[9]) then
begin
Suma:= StrToInt(Cif[3])+StrToInt(Cif[5])+StrToInt(Cif[7]);
for n := 1 to 4 do
Suma := Suma + ((2*StrToInt(Cif[2*n])) mod 10)+((2*StrToInt(Cif[2*n])) div 10);
Control := 10 - (Suma mod 10);
if Pos(Cif[1],'PS')<>0 then
Result := (Cif[9] = Chr(64+Control))
else
begin
if Control = 10 then
Control := 0;
Result:= ( StrToInt(Cif[9]) = Control);
end;
end
else
Result:=False;
end;
end;
end;
Y para usarlo un ejemplo sería este: (yo lo compruebo al salir del Edit)
Código Delphi
[-]
procedure TFormX.DBEditNifExit(Sender: TObject);
begin
DBEditNif.text:= CadLimpiaCar(DBEditNif.text); if not ValidaCif(DBEditNif.text) then
begin
MessageDlg('El Cif introducido es incorrecto',mtError, [MBOK],0);
DBEditNif.Clear;
end;
end;
Gracias a todos, Saludos.