Last active
September 6, 2024 10:27
-
-
Save Pipas/69ab5b514a53a494ec2a80669e950569 to your computer and use it in GitHub Desktop.
Validação de NIF Portugal com Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function validateNIF(nif) | |
| { | |
| if(!['1', '2', '3', '5', '6', '8'].includes(nif.substr(0,1)) && | |
| !['45', '70', '71', '72', '77', '79', '90', '91', '98', '99'].includes(nif.substr(0,2))) | |
| return false; | |
| let total = nif[0] * 9 + nif[1] * 8 + nif[2] * 7 + nif[3] * 6 + nif[4] * 5 + nif[5] * 4 + nif[6] * 3 + nif[7] * 2; | |
| let modulo11 = total - parseInt(total / 11) * 11; | |
| let comparador = modulo11 == 1 || modulo11 == 0 ? 0 : 11 - modulo11; | |
| return nif[8] == comparador | |
| } |
Muito grato!
Ps: Talvez o uso de === (datatype check) seja melhor para evitar mensagens do eslint. ;)
A mesma função, mas preparada para Typescript: https://gist.github.com/esaramago/de08f44188bbeb89611809680598c9e2
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typescript version:
function validateNIF(nif: string): boolean { if (!['1', '2', '3', '5', '6', '8'].includes(nif.substr(0, 1)) && !['45', '70', '71', '72', '77', '79', '90', '91', '98', '99'].includes(nif.substr(0, 2))) { return false; } const total = Number(nif[0]) * 9 + Number(nif[1]) * 8 + Number(nif[2]) * 7 + Number(nif[3]) * 6 + Number(nif[4]) * 5 + Number(nif[5]) * 4 + Number(nif[6]) * 3 + Number(nif[7]) * 2; const modulo11 = total - Math.trunc(total / 11) * 11; const comparador = modulo11 === 1 || modulo11 === 0 ? 0 : 11 - modulo11; return Number(nif[8]) === comparador; }