Skip to content

Instantly share code, notes, and snippets.

@JohanObrink
Created June 18, 2013 09:03
Show Gist options
  • Save JohanObrink/5803815 to your computer and use it in GitHub Desktop.
Save JohanObrink/5803815 to your computer and use it in GitHub Desktop.
Verify swedish personal id
var numonly = /\d{1,12}/;
// personalid.verify
// -------------------
// Takes a personal number and checks it.
// true - personal number is well formed and complete
// false - personal number is not well formed
// null - personal number is well formed but not complete
var verify = function(num) {
// empty string is undecided
if(num.length === 0) {
return null;
}
// non numerics is invalid
if(num.match(numonly)[0] !== num) {
return false;
}
// shorter than 8 is undecided
if(num.length < 8) {
return null;
}
// 8 or higher - evaluate date
var year = parseInt(num.substr(0, 4), 10);
var month = parseInt(num.substr(4, 2), 10) -1;
var day = parseInt(num.substr(6, 2), 10);
var date = new Date(year, month, day);
if(date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
return false;
}
// < 12
if(num.length < 12) {
return null;
}
// checksum
return (num
.substring(2)
.split('')
.reduce(function(tot, cur, index) {
return tot + (parseInt(cur, 10) * (2 - (index%2)));
}, '')
.split('')
.reduce(function(tot, cur) {
return tot + parseInt(cur, 10);
}, 0) % 10) === 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment