validation.nhs-number
Check an NHS number's modulus 11 check digit and normalise it to ten digits.
1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra
Pinned by 17 tests, run in TypeScript, Python and Rust.
What it does
Checks the modulus 11 check digit of an NHS number (England, Wales and the Isle of Man) and returns it as ten plain digits and in the 3-3-4 form the NHS displays it in.
A PASS IS NOT A PATIENT. The check digit catches a mistyped digit and most transpositions. Whether the number was issued, and to whom, is a Personal Demographics Service question.
For example
nhs_number(9434765919)→ valid true, normalised 9434765919, formatted 943 476 5919, reason — the NHS's own example number, as digitsnhs_number(943 476 5919)→ valid true, normalised 9434765919, formatted 943 476 5919, reason — the same number in the 3-3-4 display formnhs_number( 943-476-5919 )→ valid true, normalised 9434765919, formatted 943 476 5919, reason — hyphenated, with stray spaces around it
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 nhs_number(value: &str) -> NhsNumber
| value | string | ten digits, optionally spaced or hyphenated: "943 476 5919" |
| returns | NhsNumber |
The type it declares, generated into your project
/// normalised and formatted are null when valid is false.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NhsNumber {
pub valid: bool,
/// ten digits, no separators: "9434765919"
pub normalised: Option<String>,
/// the 3-3-4 display form: "943 476 5919"
pub formatted: Option<String>,
/// null when valid; empty, bad-character, bad-length, bad-check-digit or placeholder
pub reason: Option<String>,
}
Your code names it in one line, in the file that uses it
fune!(validation.nhs-number@^1); // then call nhs_number(…)
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
/// NHS Data Dictionary, NHS NUMBER: the first nine digits are weighted 10
/// down to 2.
const WEIGHTS: [i64; 9] = [10, 9, 8, 7, 6, 5, 4, 3, 2];
fn invalid(reason: &str) -> NhsNumber {
NhsNumber {
valid: false,
normalised: None,
formatted: None,
reason: Some(reason.to_string()),
}
}
/// Check an NHS number's modulus 11 check digit.
///
/// A pass means the number is well formed, not that it was issued or that it
/// belongs to the patient in front of you: that is a Personal Demographics
/// Service trace. Checks run in a fixed order (characters, length, check
/// digit, placeholder) so every language reports the same first reason.
pub fn nhs_number(value: &str) -> NhsNumber {
let mut digits: Vec<i64> = Vec::new();
for ch in value.chars() {
// NHS numbers are displayed 3-3-4 with spaces, and some systems print
// hyphens; both are ignored anywhere.
if ch == ' ' || ch == '-' {
continue;
}
if !ch.is_ascii_digit() {
return invalid("bad-character");
}
digits.push(ch as i64 - 48);
}
if digits.is_empty() {
return invalid("empty");
}
if digits.len() != 10 {
return invalid("bad-length");
}
let total: i64 = digits.iter().zip(WEIGHTS.iter()).map(|(d, w)| d * w).sum();
let mut check = 11 - total % 11;
// 11 means a check digit of 0. 10 means no number with these first nine
// digits is ever issued, so there is nothing the tenth digit can match.
if check == 11 {
check = 0;
}
if check == 10 || check != digits[9] {
return invalid("bad-check-digit");
}
// 0000000000 and 1111111111 both satisfy the arithmetic and are the
// placeholders people type to get past a mandatory field.
if digits.iter().all(|d| *d == digits[0]) {
return invalid("placeholder");
}
let text: String = digits.iter().map(|d| char::from(b'0' + *d as u8)).collect();
let formatted = format!("{} {} {}", &text[0..3], &text[3..6], &text[6..10]);
NhsNumber {
valid: true,
normalised: Some(text),
formatted: Some(formatted),
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 nhs_number_to_value(result: &NhsNumber) -> 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)),
("formatted", text(&result.formatted)),
("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.
nhs_number_to_value(&nhs_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.nhs-number
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./validation.nhs-number-1.0.0-rust.fune, or fetch it from a terminal with fune pull validation.nhs-number@1.0.0:rust.
The whole function, every language, is one file too: validation.nhs-number-1.0.0.fune, 14,810 bytes, sha256 6dd6e144b2dba0762c799c75588b9aebbbb91474bd336f24a06c99f8f9686ff5. 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.nhs-number
after — your function gets the result and the arguments, and returns the final result.
// fune: after validation.nhs-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.nhs-number --steps.
// fune: step validation.nhs-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.
| Case | Arguments | Expected | |
|---|---|---|---|
| the NHS's own example number, as digits | 9434765919 | → | valid true, normalised 9434765919, formatted 943 476 5919, reason — |
| the same number in the 3-3-4 display form | 943 476 5919 | → | valid true, normalised 9434765919, formatted 943 476 5919, reason — |
| hyphenated, with stray spaces around it | 943-476-5919 | → | valid true, normalised 9434765919, formatted 943 476 5919, reason — |
| an England and Wales range number whose check digit is simply 4 | 4000000004 | → | valid true, normalised 4000000004, formatted 400 000 0004, reason — |
| remainder 0 gives 11, which becomes check digit 0 | 4000000020 | → | valid true, normalised 4000000020, formatted 400 000 0020, reason — |
| remainder 1 gives 10: no tenth digit can make this number valid, not even 0 | 4000000080 | → | valid false, normalised —, formatted —, reason bad-check-digit |
| remainder 1 gives 10, so a tenth digit of 1 fails too | 4000000081 | → | valid false, normalised —, formatted —, reason bad-check-digit |
| the example with its check digit off by one | 9434765918 | → | valid false, normalised —, formatted —, reason bad-check-digit |
| the example with its first two digits transposed | 4934765919 | → | valid false, normalised —, formatted —, reason bad-check-digit |
| all zeros passes the arithmetic but is a placeholder | 0000000000 | → | valid false, normalised —, formatted —, reason placeholder |
Show the other 7 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| all ones passes the arithmetic too, and is also a placeholder | 111 111 1111 | → | valid false, normalised —, formatted —, reason placeholder |
| nine digits | 943476591 | → | valid false, normalised —, formatted —, reason bad-length |
| eleven digits | 94347659190 | → | valid false, normalised —, formatted —, reason bad-length |
| a letter O typed for a zero | 4OOOOOOOO4 | → | valid false, normalised —, formatted —, reason bad-character |
| a dot is not an accepted separator | 943.476.5919 | → | valid false, normalised —, formatted —, reason bad-character |
| the empty string | → | valid false, normalised —, formatted —, reason empty | |
| separators and nothing else | - | → | valid false, normalised —, formatted —, reason empty |
More from the author
## The check (NHS Data Dictionary, NHS NUMBER)
Multiply the first nine digits by 10, 9, 8, 7, 6, 5, 4, 3 and 2 and add them up. Take the remainder on dividing by 11 and subtract it from 11. A result of 11 means a check digit of 0. A result of 10 means the number is invalid, and no tenth digit can rescue it: an implementation that folds 10 into 0 would wrongly accept "4000000080". Otherwise the result must equal the tenth digit.
## Beyond the Data Dictionary
Numbers made of one repeated digit are refused as `placeholder`, even though 0000000000 and 1111111111 satisfy the arithmetic, because they are what people type to get past a mandatory field. This is the one rule here that the Data Dictionary does not state.
Nothing else is refused by range. Scotland's CHI numbers and Northern Ireland's Health and Care numbers use the same ten-digit modulus 11 scheme, so they pass too; if you need England and Wales numbers only, check the issuing range yourself. Test numbers in the 999 range pass as well.
## Input and result
ASCII spaces and hyphens are ignored anywhere. Any other character is `bad-character`. Validators answer rather than throw.
| reason | meaning (checked in this order) | |---|---| | `empty` | nothing but separators, or not a string | | `bad-character` | a character other than a digit, space or hyphen | | `bad-length` | not ten digits | | `bad-check-digit` | the modulus 11 check fails, including the "10" case | | `placeholder` | all ten digits the same |
## Source
NHS England, NHS Data Model and Dictionary, attribute "NHS NUMBER" (page published 15 July 2026, read 22 September 2026): https://www.datadictionary.nhs.uk/attributes/nhs_number.html
Files
| Path | Bytes |
|---|---|
| README.md | 2,062 |
| impl/python.py | 2,011 |
| impl/rust.rs | 3,025 |
| impl/typescript.ts | 1,975 |
| vectors.json | 3,046 |