If you've ever built a form for a Portuguese user, you've met the NIF (Número de Identificação Fiscal), the 9-digit tax number that shows up on invoices, sign-up forms, checkouts and HR systems.
And if you've ever validated it, you've probably done one of two things:
- Checked that it has 9 digits and called it a day, or
- Copied a snippet from a forum, pasted it into a
utils.jsand hoped for the best.
I did both, more than once, in different projects. So I turned it into a small npm package: @edyspider/validate-nif.
TL;DR
npm i @edyspider/validate-nif
import { validateNIF, randomNIF } from '@edyspider/validate-nif';
validateNIF('123456789'); // true
validateNIF('999999999'); // false
randomNIF(); // e.g. '264586522'
- Zero runtime dependencies
- Works with ES modules, CommonJS and TypeScript (types included)
- Runs in Node.js 22.12+, Bun, Deno and the browser
Why "9 digits" is not enough
A NIF is not just any 9-digit number. It has two rules you can check without calling any external service:
1. The prefix tells you what kind of entity it is. A valid NIF starts with:
| Prefix | Meaning |
|---|---|
1, 2, 3
|
Individual (singular person) |
45 |
Non-resident individual |
5 |
Company (collective person) |
6 |
Public body |
70, 74, 75
|
Inheritance (herança indivisa) |
71 |
Non-resident company |
72 |
Investment funds |
77 |
Temporary assignment by the tax office |
79 |
Exceptional regime |
8 |
Sole trader (empresário em nome individual, no longer issued) |
90, 91
|
Condominiums and irregular companies |
98 |
Non-residents without permanent establishment |
99 |
Civil companies without legal personality |
So 000000000 or 400000000 can never be valid, no matter what.
2. The last digit is a check digit (mod 11). Multiply the first 8 digits by the weights 9, 8, 7, 6, 5, 4, 3, 2, add them up, and take the remainder of dividing by 11:
- if the remainder is 0 or 1, the check digit is
0; - otherwise, it's
11 - remainder.
Here's 123456789 worked out:
1×9 + 2×8 + 3×7 + 4×6 + 5×5 + 6×4 + 7×3 + 8×2 = 156
156 mod 11 = 2
11 - 2 = 9 ✅ matches the last digit
In code, that's the whole core of the package:
const WEIGHTS = [9, 8, 7, 6, 5, 4, 3, 2];
function computeCheckDigit(base) {
const sum = WEIGHTS.reduce(
(total, weight, index) => total + Number(base[index]) * weight,
0,
);
const remainder = sum % 11;
return remainder < 2 ? 0 : 11 - remainder;
}
This catches most typos: a single wrong digit or two swapped neighbours will almost always fail the check. It does not tell you whether the NIF actually belongs to someone. For that you need the tax authority. But it stops obviously broken data before it reaches your database.
Using it in a real form
validateNIF() accepts unknown and only returns true for a string in the right format, so you can hand it raw input without guarding first:
validateNIF(123456789); // false, numbers are rejected on purpose
validateNIF(null); // false
validateNIF(' 123456789 '); // false, clean the input first
Numbers are rejected on purpose: a NIF is an identifier, not a quantity, and treating it as a string avoids surprises with leading zeros or number parsing.
If you use Zod, it plugs straight into a schema:
import { z } from 'zod';
import { validateNIF } from '@edyspider/validate-nif';
const customerSchema = z.object({
name: z.string().min(1),
nif: z
.string()
.transform((value) => value.replace(/\s/g, ''))
.refine(validateNIF, { message: 'Invalid NIF' }),
});
Prefer CommonJS? That works too:
const { validateNIF } = require('@edyspider/validate-nif');
Or straight from a CDN, no bundler needed:
import { validateNIF } from 'https://cdn.jsdelivr.net/npm/@edyspider/validate-nif@2/+esm';
Generating test data with randomNIF()
The other half of the package is randomNIF(), which returns a random valid NIF. I use it for:
- seeding a development database;
- unit and end-to-end tests that need a NIF that passes validation;
- demo environments where you don't want real people's tax numbers.
import { randomNIF } from '@edyspider/validate-nif';
const fakeCustomer = {
name: 'Test Customer',
nif: randomNIF(), // passes validateNIF(), belongs to nobody in particular
};
It picks from every valid prefix, including the two-digit ones (45, 70–79, 90–99), so your tests cover more than just the common 1 and 2.
What changed in v2
I first published this package in 2024. Version 2.0.0 is a rewrite to bring it up to date:
-
Native ES module with a CommonJS entry point, so both
importandrequire()work - TypeScript types included for both
- No runtime dependencies: webpack, Babel and Jest are gone
- Tests use the built-in Node.js test runner and cover every valid prefix
- Releases are published from GitHub Actions with npm provenance, so you can verify the package on npm was built from the public source
If you were on 1.x and used a deep import like @edyspider/validate-nif/dist/bundle.js, switch to the main entry point. The full list is in the changelog.
Try it without installing anything
If you just need to check or generate a NIF right now, there's an online version on my site: edyspider.com/tools/nif.
What's next in this series
The NIF is only one of the Portuguese numbers that forms ask for. Coming up next:
-
NISS, the social security number, with
@edyspider/validate-niss -
NIB and IBAN, plus finding the bank's SWIFT/BIC from the account number, with
@edyspider/validate-bank-account-pt
Follow the series so you don't miss them.
- 📦 npm: @edyspider/validate-nif
- 💻 GitHub: edyspider/validate-nif
Found a bug or an edge case I missed? Open an issue or tell me in the comments. And if this saves you from writing yet another utils/validateNif.js, a ⭐ on GitHub is always appreciated.
Top comments (0)