[Delphi] Controllo correttezza Partita Iva e Codice Fiscale

In questo articolo riporto due funzioni utili a chi sviluppa in Delphi e desidera effettuare un controllo sulla validità formale del codice fiscale e/o della partita iva.

Partita Iva
Function PartitaIVA(Const P_IVA:string):boolean;
Var
 c, j, i : integer;
begin
 Result := False;
 if Length(P_IVA) <> 11 then Exit;
 for i := 1 to Length(P_IVA) do
  if not (P_IVA[i] in ['0'..'9']) then Exit;
j := 0;
 c := 0;
 for i := 1 to 10 do begin
  if Odd(i) then begin
  j := j + Ord(P_IVA[i]) - 48
  end else begin
  c := 2 * (Ord(P_IVA[i]) - 48);
  j := j + (c div 10) + (c mod 10);
  end;
 end;
c := j mod 10;
 if c <> 0 then c := 10 - c;
 if (P_IVA[11] = Chr(c + 48)) then Result := True;
end;


Codice Fiscale
Function CodiceFiscale(Const ToCheck: string):Boolean;
Const ControlloDispari: array['0'..'Z'] of byte = (
                1,0,5,7,9,13,15,17,19,21,
                0,0,0,0,0,0,0,
                1,0,5,7,9,13,15,17,19,21,2,4,18,20,11,
                3,6,8,12,14,16,10,22,25,24,23 );
ControlloPari : array['0'..'Z'] of byte = (
                0,1,2,3,4,5,6,7,8,9,
                0,0,0,0,0,0,0,
                0,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);
Var i, k : integer;
begin
   if Length(ToCheck) <> 16 then
      Abort;
      k := 0;
       for i := 1 to 15 do
         begin
          if Odd(i) then
            Inc(k, ControlloDispari[ToCheck[i]])
          else
            Inc(k, ControlloPari[ToCheck[i]]);
         end;
    Result := (chr(65 + k mod 26) = ToCheck[16]);
end;

Lascia un commento

Occorre aver fatto il login per inviare un commento