Skip to content

Instantly share code, notes, and snippets.

@eresende
Last active April 11, 2024 15:49
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save eresende/88562d2c4dc85b62cb0c to your computer and use it in GitHub Desktop.
Save eresende/88562d2c4dc85b62cb0c to your computer and use it in GitHub Desktop.
Validação de NIF Portugal com Javascript
/*
Source: http://www.portugal-a-programar.pt/topic/58852-algoritmo-de-validacao-de-nif-pt/
*/
function validaContribuinte(contribuinte){
// algoritmo de validação do NIF de acordo com
// http://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal
var temErro=0;
if (
contribuinte.substr(0,1) != '1' && // pessoa singular
contribuinte.substr(0,1) != '2' && // pessoa singular
contribuinte.substr(0,1) != '3' && // pessoa singular
contribuinte.substr(0,2) != '45' && // pessoa singular não residente
contribuinte.substr(0,1) != '5' && // pessoa colectiva
contribuinte.substr(0,1) != '6' && // administração pública
contribuinte.substr(0,2) != '70' && // herança indivisa
contribuinte.substr(0,2) != '71' && // pessoa colectiva não residente
contribuinte.substr(0,2) != '72' && // fundos de investimento
contribuinte.substr(0,2) != '77' && // atribuição oficiosa
contribuinte.substr(0,2) != '79' && // regime excepcional
contribuinte.substr(0,1) != '8' && // empresário em nome individual (extinto)
contribuinte.substr(0,2) != '90' && // condominios e sociedades irregulares
contribuinte.substr(0,2) != '91' && // condominios e sociedades irregulares
contribuinte.substr(0,2) != '98' && // não residentes
contribuinte.substr(0,2) != '99' // sociedades civis
) { temErro=1;}
var check1 = contribuinte.substr(0,1)*9;
var check2 = contribuinte.substr(1,1)*8;
var check3 = contribuinte.substr(2,1)*7;
var check4 = contribuinte.substr(3,1)*6;
var check5 = contribuinte.substr(4,1)*5;
var check6 = contribuinte.substr(5,1)*4;
var check7 = contribuinte.substr(6,1)*3;
var check8 = contribuinte.substr(7,1)*2;
var total= check1 + check2 + check3 + check4 + check5 + check6 + check7 + check8;
var divisao= total / 11;
var modulo11=total - parseInt(divisao)*11;
if ( modulo11==1 || modulo11==0){ comparador=0; } // excepção
else { comparador= 11-modulo11;}
var ultimoDigito=contribuinte.substr(8,1)*1;
if ( ultimoDigito != comparador ){ temErro=1;}
if (temErro==1){ alert('O numero de contribuinte parece estar errado' ); }
}
@ivomiguelP
Copy link

Obrigado pelo código. 👍 👍 👍

@FranciscoCaldeira
Copy link

🇵🇹 Aqui deixo um CodePen exemplo com um helper minimalista para validar apenas NIFs pessoais:
👉 https://codepen.io/caneco/pen/gOMZvqQ

O exemplo usa apenas TailwindCSS e AlpineJS 😉

Boas, tenho este nif 719209374, que não é válido com a tua solução.
Cumprimentos,

@caneco
Copy link

caneco commented Feb 25, 2021

@FranciscoCaldeira, no exemplo estou apenas a considerar NIF pessoais.

Para resolver basta alterar o RegEx:

// alterar a linha 8 de:
if (!/^[123]|45|5/.test(value)) return false;

// para:
if (!/^[123]|45|5|7/.test(value)) return false;

@Jeconias
Copy link

Jeconias commented Apr 15, 2021

Following this gist, I created a simple function to validate with TS.

const validateNIF = (value: string | undefined) => {
  if (!value || typeof value !== "string" || value.length !== 9) return false;

  let sumAux = 0;
  for (let i = 9; i >= 2; i--) {
    sumAux += i * (parseInt(value[value.length - i]) || 0);
  }

  const module = sumAux % 11;

  // Get the eight first numbers
  const NIFwithoutLastDigit = value.slice(0, value.length - 1);

  if (module === 0 || module === 1) {
    return `${NIFwithoutLastDigit}0` === value;
  } else {
    return `${NIFwithoutLastDigit}${11 - module}` === value;
  }
};

@zeworks
Copy link

zeworks commented Mar 2, 2023

@Jeconias 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment