惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
量子位
博客园 - 三生石上(FineUI控件)
博客园 - Franky
博客园_首页
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
G
Google Developers Blog
IT之家
IT之家
Google DeepMind News
Google DeepMind News
爱范儿
爱范儿
Last Week in AI
Last Week in AI
U
Unit 42
J
Java Code Geeks
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MyScale Blog
MyScale Blog
H
Help Net Security
V
V2EX
S
SegmentFault 最新的问题
月光博客
月光博客
Martin Fowler
Martin Fowler
Vercel News
Vercel News
Y
Y Combinator Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Validate Spanish NIF, NIE, CIF and IBAN in Any Pro...
Daniel · 2026-05-21 · via DEV Community

Daniel

How to Validate Spanish NIF, NIE, CIF and IBAN in Any Programming Language (2026)

If you're building software for the Spanish market, sooner or later you'll need to validate fiscal documents. This guide covers everything: how the algorithms work, code examples in 4 languages, and the fastest way to add validation to any project.


What are NIF, NIE and CIF?

  • NIF — Tax ID for Spanish individuals (8 digits + 1 letter, e.g. 12345678Z)
  • NIE — Tax ID for foreign residents in Spain (X/Y/Z + 7 digits + letter, e.g. X1234567L)
  • CIF — Tax ID for Spanish companies (1 letter + 7 digits + 1 control char, e.g. A28015865). Also returns the company type: S.A., S.L., Cooperative, etc.
  • IBAN — Bank account number, 24 characters for Spanish accounts (e.g. ES9121000418450200051332)

Option 1: Implement it yourself

NIF validation (JavaScript)

const NIF_LETTERS = 'TRWAGMYFPDXBNJZSQVHLCKE';

function validateNIF(nif) {
  nif = nif.trim().toUpperCase();
  if (nif.length !== 9) return false;
  const number = parseInt(nif.slice(0, 8), 10);
  if (isNaN(number)) return false;
  return nif[8] === NIF_LETTERS[number % 23];
}

console.log(validateNIF('12345678Z')); // true
console.log(validateNIF('12345678A')); // false

Enter fullscreen mode Exit fullscreen mode

NIF validation (Python)

NIF_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE"

def validate_nif(nif: str) -> bool:
    nif = nif.strip().upper()
    if len(nif) != 9:
        return False
    try:
        number = int(nif[:8])
    except ValueError:
        return False
    return nif[8] == NIF_LETTERS[number % 23]

print(validate_nif("12345678Z"))  # True

Enter fullscreen mode Exit fullscreen mode

NIF validation (PHP)

function validateNIF(string $nif): bool {
    $letters = 'TRWAGMYFPDXBNJZSQVHLCKE';
    $nif = strtoupper(trim($nif));
    if (strlen($nif) !== 9) return false;
    $number = intval(substr($nif, 0, 8));
    return $nif[8] === $letters[$number % 23];
}

var_dump(validateNIF('12345678Z')); // bool(true)

Enter fullscreen mode Exit fullscreen mode


Option 2: Use an API (3 lines of code, any language)

If you don't want to implement and maintain the algorithms yourself — especially for CIF which is significantly more complex — you can use the Spain Document Validator API on RapidAPI. It's free for up to 500 requests/month.

JavaScript (fetch)

const response = await fetch(
  'https://spain-document-validator.p.rapidapi.com/validate/nif?value=12345678Z',
  {
    headers: {
      'X-RapidAPI-Key': 'YOUR_API_KEY',
      'X-RapidAPI-Host': 'spain-document-validator.p.rapidapi.com'
    }
  }
);
const data = await response.json();
console.log(data);
// { input: '12345678Z', valid: true, type: 'NIF' }

Enter fullscreen mode Exit fullscreen mode

Python (requests)

import requests

response = requests.get(
    'https://spain-document-validator.p.rapidapi.com/validate/cif',
    params={'value': 'A28015865'},
    headers={
        'X-RapidAPI-Key': 'YOUR_API_KEY',
        'X-RapidAPI-Host': 'spain-document-validator.p.rapidapi.com'
    }
)
print(response.json())
# {'input': 'A28015865', 'valid': True, 'type': 'CIF', 'entity_type': 'Sociedad Anónima'}

Enter fullscreen mode Exit fullscreen mode

PHP (cURL)

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => 'https://spain-document-validator.p.rapidapi.com/validate/iban?value=ES9121000418450200051332',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-RapidAPI-Key: YOUR_API_KEY',
        'X-RapidAPI-Host: spain-document-validator.p.rapidapi.com'
    ],
]);
$response = json_decode(curl_exec($curl));
// $response->bank_name = "CaixaBank"

Enter fullscreen mode Exit fullscreen mode


API response examples

NIF:

{ "input": "12345678Z", "valid": true, "type": "NIF" }

Enter fullscreen mode Exit fullscreen mode

CIF:

{
  "input": "A28015865",
  "valid": true,
  "type": "CIF",
  "entity_type": "Sociedad Anónima"
}

Enter fullscreen mode Exit fullscreen mode

IBAN:

{
  "input": "ES9121000418450200051332",
  "valid": true,
  "type": "IBAN",
  "country": "ES",
  "formatted": "ES91 2100 0418 4502 0005 1332",
  "bank_code": "2100",
  "branch_code": "0418",
  "bank_name": "CaixaBank"
}

Enter fullscreen mode Exit fullscreen mode


When to use the API vs implementing it yourself

DIY API
Setup time 2-4 hours 5 minutes
Works in any language Requires separate lib per lang Yes
CIF entity type info Extra work Included
IBAN bank name lookup Very complex Included
Maintenance when rules change Your problem Automatic

The free tier (500 req/month) is enough for most small projects. Paid plans start at $9/month for 15,000 requests.


The full API documentation and interactive playground is available at spanish-validation-api.vercel.app/docs.