Validating Finnish Social Security Numbers

December 15, 2009

Just in case someone else needs this - here’s one, fairly elegant way to validate Finnish SSN’s, in JavaScript:

/**
 * Check Finnish social security number
 * @return true if correct, false if incorrect, -1 if malformed
 */
function checkSsn(ssn)
{
  ssn = ssn.toLowerCase();
  m = ssn.match(/(\d{6})-(\d{3})(\w){1}/);

  if (!m) {
    return -1;
  }

  c = Array(); base = 35;
  n = parseInt(m[1] + m[2], 10) % 31;

  for (i = 0; i < base; i++)  {
    e = parseInt(i, 10).toString(base);
    if ('gioq'.indexOf(e) < 0) {
      c.push(e);
    }
  }

  return (c[n] == m[3]);

}

The idea is the last character in the SSN is essentially a verification code derived from all the numbers in the SSN. The specs are from the Finnish Population Register Center but unfortunately they only seem to be available in Finnish.