Last active
June 2, 2016 19:54
-
-
Save RomansBermans/604e1dd387dd4112a3aae69b73eeda8b to your computer and use it in GitHub Desktop.
NHS Number Validator in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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