Skip to content

Instantly share code, notes, and snippets.

@RomansBermans
Last active June 2, 2016 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RomansBermans/604e1dd387dd4112a3aae69b73eeda8b to your computer and use it in GitHub Desktop.
Save RomansBermans/604e1dd387dd4112a3aae69b73eeda8b to your computer and use it in GitHub Desktop.
NHS Number Validator in JavaScript
function isValidNHSNumber(number) {
number = (number + '').replace(/\D/g, '');
if(number.length == 10) {
let total = 0;
// STEP 1: Starting from the left, multiply each of the first nine digits by (11 - digit position).
for(let i = 1; i <= 9; i++) {
const digit = number.substr(i - 1, 1);
const factor = 11 - i;
// STEP 2: Add the results of each multiplication together.
total += (digit * factor);
}
// STEP 3: Divide the total by 11 and establish the remainder.
const reminder = total % 11;
// STEP 4: Subtract the remainder from 11 to give the check digit. If the result is 11 then a check digit of 0 is used. If the result is 10 then the NHS number is invalid and not used.
let checkDigit = 11 - reminder;
if(checkDigit == 11) {
checkDigit = 0;
}
// STEP 5: Check if the check digit matches the last digit. If it does not, the NHS number is invalid.
if(checkDigit == number.substr(9, 1)) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment