Skip to content

Instantly share code, notes, and snippets.

@ahultgren
Created January 20, 2014 16:31
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 ahultgren/8523436 to your computer and use it in GitHub Desktop.
Save ahultgren/8523436 to your computer and use it in GitHub Desktop.
Validerar svenska personnummer. Kollar längd, att det är ett giltigt datum samt validerar checksumman.
(function (exports) {
function validatePersonnummer (personnummer) {
// Ensure string in case of number
personnummer = "" + personnummer;
// Trim non-digits
// This discards (and thus accepts) any non-digits anywhere in the personnummer.
// Depending on your case, that might not be the desired behavior.
personnummer = personnummer.replace(/[^\d]/g, '');
// Return true if both a valid date and has a valid checksum
return hasValidLength(personnummer) &&
hasValidDate(personnummer) &&
hasValidChecksum(personnummer);
}
function hasValidLength (personnummer) {
// Ensure there's 10 or 12 digits
return personnummer.length === 10 || personnummer.length === 12;
}
function hasValidDate (personnummer) {
var date, year, month, day;
// Pad it to 12 digits so we have a real year
if(personnummer.length === 10) {
personnummer = '19' + personnummer;
}
// Extract year/month/date and convert to number
year = +personnummer.substring(0, 4);
month = +personnummer.substring(4, 6) - 1; // Js-month is one less
day = +personnummer.substring(6, 8);
date = new Date(year, month, day);
if(!+date) {
return false;
}
// Now test that no year/month/day has overflowed. If it has, the date was invalid
return year === date.getFullYear() &&
month === date.getMonth() &&
day === date.getDate();
}
function hasValidChecksum (numbers) {
var n, i, l,
checksum = 0;
// Accept a 12-length personnummer, but always start with the two last digits
// of the year
for(i = numbers.length - 10, l = numbers.length; i < l; i++) {
n = +numbers[i];
if(i % 2 === 0) {
checksum += (n * 2) % 9 + ~~(n / 9) * 9;
}
else {
checksum += n;
}
}
return checksum % 10 === 0;
}
// Some hack to support both node and browsers
exports = validatePersonnummer;
}(typeof module !== 'undefined' && module.exports || window.validatePersonnummer));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment