Skip to content

feat: add Spanish DNI/NIF generator to ID generator - #1906

Open
SetyVII wants to merge 2 commits into
datafaker-net:mainfrom
SetyVII:main
Open

feat: add Spanish DNI/NIF generator to ID generator#1906
SetyVII wants to merge 2 commits into
datafaker-net:mainfrom
SetyVII:main

Conversation

@SetyVII

@SetyVII SetyVII commented Sep 4, 2026

Copy link
Copy Markdown

Summary

This PR adds support for generating Spanish DNI/NIF identification numbers.

Faker faker = new Faker(Locale.forLanguageTag("es-ES"));

String validDni = faker.idNumber().valid();
String invalidDni = faker.idNumber().invalid();

This initial implementation covers the standard DNI/NIF format for Spanish
nationals.

Tests for Spanish ID number generation are included.

Official references:

@what-the-diff

what-the-diff Bot commented Sep 4, 2026

Copy link
Copy Markdown

PR Summary

  • Inclusion of Spanish National Identity Number Class
    A new class, designed specifically for handling Spanish National Identity Numbers (also known as DNI/NIF), has been added. This aids in the production of both valid and non-valid numbers.
  • Incorporation of IdNumberGenerator Interface
    This interface is now implemented in our newly added SpanishIdNumber class. It equipped the class with methods to generate both valid and invalid Spanish identification numbers.
  • Inclusion of Checksum Logic
    A self-contained method that calculates the check letter for Spanish ID numbers was embedded. This calculation is based on a predesignated set of letters.
  • Service Configuration Update
    The existing IdNumberGenerator file has been modified to include our new SpanishIdNumber class. This allows it to be acknowledged throughout the application context.
  • Updated Identification Number Patterns
    A new validation pattern has been added to the IdNumberPatterns class to accommodate Spanish DNI.
  • Addition of Spanish ID Test Class
    A thorough test class has been produced to validate the functionality of the SpanishIdNumber class. The tests check for checksum validity and for the capability to generate valid as well as invalid ID numbers.
  • Enhancement of Existing Identification Number Test Class
    Supplemental tests have been added to the existing IdNumberTest to check the validity of the Spanish ID numbers within the larger framework.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.35%. Comparing base (14edbe2) to head (fd462f1).
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #1906      +/-   ##
============================================
+ Coverage     92.28%   92.35%   +0.06%     
- Complexity     3597     3604       +7     
============================================
  Files           348      349       +1     
  Lines          7115     7127      +12     
  Branches        695      695              
============================================
+ Hits           6566     6582      +16     
+ Misses          376      374       -2     
+ Partials        173      171       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@kingthorin

kingthorin commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

Grok review:
(Lost some of the formatting, sorry)

PR Review: #1906 – feat: add Spanish DNI/NIF generator to ID generator

Author: SetyVII
Summary: Adds support for generating Spanish DNI/NIF (Documento Nacional de Identidad / Número de Identificación Fiscal) numbers via the existing IdNumber provider. It supports both valid and invalid numbers for the standard 8-digit + check-letter format used by Spanish nationals.

What the PR does

  • New class SpanishIdNumber implementing IdNumberGenerator.
  • Registers it in META-INF/services/net.datafaker.idnumbers.IdNumberGenerator.
  • Adds SPANISH pattern to IdNumberPatterns.
  • Adds dedicated unit tests (SpanishIdNumberTest) + integration-style tests in IdNumberTest.

Usage example (from PR description):

Faker faker = new Faker(Locale.forLanguageTag("es-ES"));
String validDni = faker.idNumber().valid();
String invalidDni = faker.idNumber().invalid();

Correctness of the algorithm
The checksum is correct and matches the official Spanish algorithm:

  • Take the 8-digit number.
  • Compute number % 23.
  • Map the remainder (0–22) to the letter string "TRWAGMYFPDXBNJZSQVHLCKE".

This is confirmed by official sources (Spanish Ministry of the Interior) and multiple independent validators.

The provided test cases also match known examples:

  • 00000000 → T
  • 00000001 → R
  • 12345678 → Z
  • 99999999 → R

Invalid generation is also solid: it deliberately picks the next letter in the cycle so the checksum fails while still matching the regex.

Code quality & consistency
Positive:

  • Follows the same structure as other generators (NorwegianIdNumber, etc.).
  • Uses the shared Utils.birthday() / Utils.gender() helpers.
  • Returns a proper PersonIdNumber (even though Spanish DNI does not encode birth date or gender).
  • Clean, minimal implementation.
  • Good documentation with official links.
  • Service loader registration is correct.
  • Pattern is accurate: \d{8}[TRWAGMYFPDXBNJZSQVHLCKE].

Minor observations / suggestions:

  1. Method signature mismatch in tests
    In SpanishIdNumberTest:
String generated = generator.generateValid(faker); // only one argument

  2. The interface method is generateValid(BaseProviders faker, IdNumberRequest request).
Either there is a default method in the interface, or this test will not compile. Worth double-checking.

  3. NIE support is missing
The PR only covers DNI/NIF for Spanish nationals (8 digits + letter).
Foreign residents use NIE (X/Y/Z + 7 digits + letter). The same checksum algorithm applies after mapping X→0, Y→1, Z→2.
The description correctly says “This initial implementation covers the standard DNI/NIF format”, so this is fine as a first step, but it would be nice to mention NIE as future work (or add it).

  4. No leading zeros concern
faker.number().digits(8) correctly produces zero-padded strings, which is important (e.g. 00000000T is valid).

  5. Checksum method visibility static char checksum(...) is package-private. Making it public (or keeping it package-private) is fine given the tests live in the same package.

  6. Locale
The test uses new Locale("es", "ES"), which is correct. The PR description uses Locale.forLanguageTag("es-ES") — both work.
    Test coverage

  • Checksum unit tests with known values → excellent.
  • 100× repeated tests for both valid and invalid → good.
  • Integration tests in IdNumberTest → good.
  • Pattern matching is verified.

@asolntsev asolntsev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But check Grok's comment.

@asolntsev asolntsev added this to the 3.0.0 milestone Sep 4, 2026
@asolntsev asolntsev added the enhancement New feature or request label Sep 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants