Skip to content

Instantly share code, notes, and snippets.

@diogoalexsmachado
Last active June 1, 2021 08:11
Show Gist options
  • Save diogoalexsmachado/32827e01127e0b478f482dbd15bb0d13 to your computer and use it in GitHub Desktop.
Save diogoalexsmachado/32827e01127e0b478f482dbd15bb0d13 to your computer and use it in GitHub Desktop.
Portuguese NIF Validation
function validateNif(nif){
// validation reference:
// http://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal
var error=0;
if (
nif.substr(0,1) != '1' && // pessoa singular
nif.substr(0,1) != '2' && // pessoa singular
nif.substr(0,1) != '3' && // pessoa singular
nif.substr(0,2) != '45' && // pessoa singular não residente
nif.substr(0,1) != '5' && // pessoa colectiva
nif.substr(0,1) != '6' && // administração pública
nif.substr(0,2) != '70' && // herança indivisa
nif.substr(0,2) != '71' && // pessoa colectiva não residente
nif.substr(0,2) != '72' && // fundos de investimento
nif.substr(0,2) != '77' && // atribuição oficiosa
nif.substr(0,2) != '79' && // regime excepcional
nif.substr(0,1) != '8' && // empresário em nome individual (extinto)
nif.substr(0,2) != '90' && // condominios e sociedades irregulares
nif.substr(0,2) != '91' && // condominios e sociedades irregulares
nif.substr(0,2) != '98' && // não residentes
nif.substr(0,2) != '99' // sociedades civis
) { error=1;}
var check1 = nif.substr(0,1)*9;
var check2 = nif.substr(1,1)*8;
var check3 = nif.substr(2,1)*7;
var check4 = nif.substr(3,1)*6;
var check5 = nif.substr(4,1)*5;
var check6 = nif.substr(5,1)*4;
var check7 = nif.substr(6,1)*3;
var check8 = nif.substr(7,1)*2;
var total= check1 + check2 + check3 + check4 + check5 + check6 + check7 + check8;
var division= total / 11;
var module11=total - parseInt(division)*11;
if ( module11==1 || module11==0){ comparator=0; }
else { comparator= 11-module11;}
var lastDigit=nif.substr(8,1)*1;
if ( lastDigit != comparator ){ error=1;}
if (error){ alert('NIF is invalid' ); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment