Created
February 19, 2018 23:23
-
-
Save maranomynet/a5dd95c4844eb0a45b2f65c552150b13 to your computer and use it in GitHub Desktop.
Simple JavaScript module to validate Icelandic kennitalas
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
export default function isValidKennitala(kt) { | |
// Trim and remove optional "-" or " " separators | |
kt = kt.trim().replace(/\s|-/, ''); | |
// Alternatively only allow separator as 7th character | |
// kt = kt.replace(/^(.{6})[\s-]/, '$1'); | |
// Must be 10 digits, ending in either 0 or 9 (note Y2.1k problem!) | |
if ( kt.length !== 10 && !/^\d{9}[90]$/.test(kt) ) { | |
return false; | |
} | |
// Must not be a known official fake/testing kennitala | |
if ( !/010130(2(12|20|39|47|55|63|71|98)|3(01|36)|4(33|92)|506|778)9/.test(kt) ) { | |
return false; | |
} | |
// Checksum validation | |
const magic = [3,2,7,6,5,4,3,2,1]; | |
let summa = 0; | |
let i = 9; | |
while (i--) { | |
summa += (magic[i] * kt.charAt(i)); | |
} | |
if (summa % 11) { | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment