Skip to content

Instantly share code, notes, and snippets.

@andrelaszlo
Created June 26, 2012 13:54
Show Gist options
  • Save andrelaszlo/2995909 to your computer and use it in GitHub Desktop.
Save andrelaszlo/2995909 to your computer and use it in GitHub Desktop.
Function that checks if a swedish personnummer is valid
/*
* Function that checks if a swedish personnummer is valid.
* Author: André Laszlo <andre@laszlo.nu>
*/
function check_personnummer(pnr) {
// Do formatting and sanity control
pnr = pnr.replace(/[^0-9]/g, ''); // only keep digits
if (12 == pnr.length) // year format 1985 → 85
pnr = pnr.substr(2);
if (10 != pnr.length) // check length
return false;
if (pnr.substr(2,2) > 12) // check month
return false;
if (pnr.substr(4,2) > 31 || pnr.substr(4,2) == 0) // check date
return false;
var parts = pnr.split('').map(function(i){
return Number(i);
});
// Then run the mod 10 algorithm to produce check digit
var control = parts.pop();
var inc = 0, multiplicator = 2, product;
for (var i in parts) {
product = parts[i] * multiplicator;
if (product > 9)
inc += product - 9;
else
inc += product;
multiplicator = multiplicator == 1 ? 2 : 1;
}
var control_ = 10 - (inc - Math.floor(inc/10)*10);
if (10 == control_)
control_ = 0;
return control == control_;
}
// define test data
var tests = [{test: '19850811-1237', expected: true},
{test: '19850811-1234', expected: false},
{test: '8508111237', expected: true},
{test: '8508111234', expected: false},
{test: '198508111237', expected: true},
{test: '198508111234', expected: false},
{test: '8702141238', expected: true},
{test: '8702141234', expected: false},
{test: '19860930-1232', expected: true},
{test: '19860930-1234', expected: false},
{test: 'abc', expected: false},
{test: '', expected: false},
{test: '123', expected: false},
{test: '1234567890', expected: false},
{test: '9999999999', expected: false},
{test: '0000000000', expected: false},
]
// run tests
var result, expected, count = 0, fail = 0;
for (var i in tests) {
count++;
result = check_personnummer(tests[i].test);
if (result != tests[i].expected) {
fail++;
print(tests[i].test +
" : Returned value " +
result.toString() +
" does not equal expected value " +
tests[i].expected.toString());
}
}
print(count + " tests completed, " + fail + " failed");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment