Functional Weave
Code in Rust

validation.uk-ni-number

Check a UK National Insurance number's format and HMRC's disallowed prefix letters, and normalise it.

1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra

Pinned by 22 tests, run in TypeScript, Python and Rust.

What it does

Checks that a UK National Insurance number (NINO) has the shape HMRC issues and uses none of the prefix letters HMRC rules out, and returns it upper case with the spaces removed, the form payroll submissions (RTI) carry.

A NINO HAS NO CHECK DIGIT. A pass means the number could have been issued; only HMRC or DWP can say it was, and to whom. Treat this as typo-catching at the keyboard.

For example

  • uk_ni_number(AB123456C) → valid true, normalised AB123456C, reason — a well-formed number
  • uk_ni_number(ab 12 34 56 c) → valid true, normalised AB123456C, reason — lower case and spaced as printed on a letter
  • uk_ni_number( JG103759A ) → valid true, normalised JG103759A, reason — stray leading and trailing spaces

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

pub fn uk_ni_number(value: &str) -> UkNiNumber
valuestringa NINO in any case, optionally spaced: "QQ 12 34 56 A"
returnsUkNiNumber

The type it declares, generated into your project

/// normalised is null when valid is false.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UkNiNumber {
    pub valid: bool,
    /// nine characters, upper case, no spaces: "AB123456C"
    pub normalised: Option<String>,
    /// null when valid; empty, bad-character, bad-length, bad-format, bad-prefix or bad-suffix
    pub reason: Option<String>,
}

Your code names it in one line, in the file that uses it

fune!(validation.uk-ni-number@^1);  // then call uk_ni_number(…)
impl/rust.rs · 88 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

/// HMRC NIM39110: D, F, I, Q, U and V are never either letter of a prefix,
/// and O is never the second.
const BARRED_FIRST: &str = "DFIQUV";
const BARRED_SECOND: &str = "DFIOQUV";

/// Prefixes made of allowed letters that HMRC still never issues.
const BARRED_PREFIXES: [&str; 7] = ["BG", "GB", "KN", "NK", "NT", "TN", "ZZ"];

/// The suffix records the quarter a contribution card was once returned in,
/// and is always one of these four.
const SUFFIXES: &str = "ABCD";

fn invalid(reason: &str) -> UkNiNumber {
    UkNiNumber {
        valid: false,
        normalised: None,
        reason: Some(reason.to_string()),
    }
}

/// Check a National Insurance number's shape and prefix rules.
///
/// There is no check digit in a NINO, so a pass means "could have been
/// issued", never "belongs to this person". The checks run in a fixed order
/// (characters, length, shape, prefix, suffix) so that every language reports
/// the same first reason.
pub fn uk_ni_number(value: &str) -> UkNiNumber {
    let mut compact: Vec<char> = Vec::new();
    for ch in value.chars() {
        // Only the ASCII space is ignored: NINOs are printed in pairs.
        if ch == ' ' {
            continue;
        }
        // ASCII-only upper-casing, so no language's Unicode rules can turn a
        // stray character into a letter that passes.
        let ch = ch.to_ascii_uppercase();
        if !ch.is_ascii_uppercase() && !ch.is_ascii_digit() {
            return invalid("bad-character");
        }
        compact.push(ch);
    }
    if compact.is_empty() {
        return invalid("empty");
    }
    if compact.len() != 9 {
        return invalid("bad-length");
    }
    if !compact[0].is_ascii_uppercase() || !compact[1].is_ascii_uppercase() || !compact[8].is_ascii_uppercase() {
        return invalid("bad-format");
    }
    if !compact[2..8].iter().all(|ch| ch.is_ascii_digit()) {
        return invalid("bad-format");
    }
    let prefix: String = compact[0..2].iter().collect();
    if BARRED_FIRST.contains(compact[0]) || BARRED_SECOND.contains(compact[1]) || BARRED_PREFIXES.contains(&prefix.as_str()) {
        return invalid("bad-prefix");
    }
    if !SUFFIXES.contains(compact[8]) {
        return invalid("bad-suffix");
    }
    UkNiNumber {
        valid: true,
        normalised: Some(compact.iter().collect()),
        reason: None,
    }
}

/// Object keys are camelCase to match the shared vectors, and so that a
/// capability building on this one can reuse the same shape.
pub fn uk_ni_number_to_value(result: &UkNiNumber) -> Value {
    let text = |field: &Option<String>| match field {
        Some(s) => Value::str(s),
        None => Value::Null,
    };
    Value::obj(vec![
        ("valid", Value::Bool(result.valid)),
        ("normalised", text(&result.normalised)),
        ("reason", text(&result.reason)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    // A non-string argument arrives here as an empty string, which is exactly
    // the answer TypeScript and Python give for a non-string: empty.
    uk_ni_number_to_value(&uk_ni_number(args[0].as_str()))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add validation.uk-ni-number
Download for Rust validation.uk-ni-number-1.0.0-rust.fune · 11,168 bytes sha256 305e6a023c1b25b5a7a21365add6f1d539980370695670ae06d480df19009704

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./validation.uk-ni-number-1.0.0-rust.fune, or fetch it from a terminal with fune pull validation.uk-ni-number@1.0.0:rust.

The whole function, every language, is one file too: validation.uk-ni-number-1.0.0.fune, 15,976 bytes, sha256 11470cb19b93bf8d071d62938dfebf56b12a1db80ab516d8437dc0426b734ebc. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before validation.uk-ni-number

after — your function gets the result and the arguments, and returns the final result.

// fune: after validation.uk-ni-number

replace — it requires no other capability, so there is no dependency to replace.

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show validation.uk-ni-number --steps.

// fune: step validation.uk-ni-number after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
a well-formed number AB123456C → valid true, normalised AB123456C, reason —
lower case and spaced as printed on a letter ab 12 34 56 c → valid true, normalised AB123456C, reason —
stray leading and trailing spaces JG103759A → valid true, normalised JG103759A, reason —
each suffix A to D is allowed; D here CE000001D → valid true, normalised CE000001D, reason —
O may start a prefix: it is only barred as the second letter OA123456B → valid true, normalised OA123456B, reason —
HMRC's own example QQ 12 34 56 A is deliberately not a valid number QQ 12 34 56 A → valid false, normalised —, reason bad-prefix
D is never a first letter DA123456A → valid false, normalised —, reason bad-prefix
V is never a second letter AV123456A → valid false, normalised —, reason bad-prefix
O is never a second letter, so the OO administrative prefix fails OO123456A → valid false, normalised —, reason bad-prefix
GB is a barred prefix although both letters are allowed GB123456A → valid false, normalised —, reason bad-prefix
Show the other 12 tests
CaseArgumentsExpected
TN, the retired temporary-number prefix, is barred TN123456A → valid false, normalised —, reason bad-prefix
ZZ is barred ZZ123456A → valid false, normalised —, reason bad-prefix
NK is barred NK123456A → valid false, normalised —, reason bad-prefix
E is not a suffix AB123456E → valid false, normalised —, reason bad-suffix
the old PP999999P pension reporting reference fails on its suffix PP999999P → valid false, normalised —, reason bad-suffix
a missing suffix is too short AB123456 → valid false, normalised —, reason bad-length
a digit where a prefix letter belongs A1123456C → valid false, normalised —, reason bad-format
a letter among the six digits AB12345CD → valid false, normalised —, reason bad-format
hyphens are not a NINO separator AB-12-34-56-C → valid false, normalised —, reason bad-character
a non-ASCII letter ÅB123456C → valid false, normalised —, reason bad-character
the empty string → valid false, normalised —, reason empty
only spaces → valid false, normalised —, reason empty

More from the author

## The rules (HMRC NIM39110)

- Two prefix letters, six digits, one suffix letter. - D, F, I, Q, U and V are never used as either prefix letter. - O is never the second prefix letter. It may be the first: "OA123456B" passes, and a validator that bans O everywhere gets this wrong. - BG, GB, KN, NK, NT, TN and ZZ are never used as prefixes. - The suffix is always A, B, C or D. Some older systems accept a blank suffix; HMRC's manual says the suffix is always present, so it is required.

HMRC's printed example, "QQ 12 34 56 A", is deliberately invalid (Q is barred), and is a vector here.

Administrative references that look like NINOs are not rejected by name. OO (tax credits) and TN (retired temporary numbers) already fail the letter rules and PP999999P fails on its suffix. FY, NC, PY and PZ are administrative prefixes the manual describes as out of use, but it does not list them as barred, so they pass. Temporary Reference Numbers ("11 a1 11 11") are not NINOs and fail.

## Input and result

Case is ignored and ASCII spaces are ignored anywhere. Anything else that is not an ASCII letter or digit (hyphens, dots, non-breaking spaces, accented letters) is `bad-character`. Validators answer rather than throw.

| reason | meaning (checked in this order) | |---|---| | `empty` | nothing but spaces, or not a string | | `bad-character` | a character other than an ASCII letter, digit or space | | `bad-length` | not nine characters once spaces are removed | | `bad-format` | not two letters, six digits and a letter | | `bad-prefix` | a barred letter or prefix | | `bad-suffix` | the last letter is not A, B, C or D |

## Source

HMRC National Insurance Manual, NIM39110 "National Insurance Numbers (NINOs): Format and Security: What a NINO looks like", read 22 September 2026: https://www.gov.uk/hmrc-internal-manuals/national-insurance-manual/nim39110

Files

PathBytes
README.md2,285
impl/python.py2,242
impl/rust.rs3,140
impl/typescript.ts2,284
vectors.json3,279