Skip to content

Instantly share code, notes, and snippets.

@jnimmo
Created March 2, 2015 00:40
Show Gist options
  • Save jnimmo/e7a0eadb05db07865b0c to your computer and use it in GitHub Desktop.
Save jnimmo/e7a0eadb05db07865b0c to your computer and use it in GitHub Desktop.
Validate New Zealand NHI Number
// Description: Returns true if a New Zealand NHI passes checksum validation, otherwise returns false.
function is_nz_nhi(NHI) {
var passTest = false;
// Validation steps 1 and 2
if (/^[A-HJ-NP-Z]{3}[0-9]{4}$/.test(NHI)) {
var checkValue = 0;
// Init alpha conversion table omitting O and I. A=1~Z=24
var aplhaTable = "ABCDEFGHJKLMNPQRSTUVWXYZ".split('');
for (i = 0; i < 3; i++) {
// Convert each letter to numeric value from table above
var letterNumeric = aplhaTable.indexOf(NHI[i]) + 1
// Multiply numeric value by 7-i and add to the checkvalue
checkValue += letterNumeric * (7 - i);
}
for (i = 3; i < 6; i++) {
// Multiply first three numbers by 7-i and add to the checkvalue
checkValue += NHI[i] * (7 - i);
}
// Apply modulus 11 to the sum of the above numbers (checkValue)
var checkSum = checkValue % 11;
// If the checksum is not 0, subtract the checksum from 11
// to create checkdigit. Mod 10 to convert 10 to 0.
if (checkSum !== 0) {
if (NHI[6] == (11 - checkSum) % 10) {
// if the last digit of the NHI matches the checkdigit, NHI is valid
passTest = true;
}
}
}
return passTest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment