Skip to content

Instantly share code, notes, and snippets.

@henhan
Created April 13, 2016 13:52
Show Gist options
  • Save henhan/b751dbe1db5e70611134c524a578856c to your computer and use it in GitHub Desktop.
Save henhan/b751dbe1db5e70611134c524a578856c to your computer and use it in GitHub Desktop.

Revisions

  1. henhan created this gist Apr 13, 2016.
    72 changes: 72 additions & 0 deletions swedishIdUtils.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    'use strict';

    function isValid(id) {
    // Make sure we have a string
    id = '' + id;
    if (id.match(/^[\-\s+\d]+$/) === null) {
    return false;
    }
    // Remove all non digits
    id = id.replace(/\D/g, '')
    if (id.length !== 10 && id.length !== 12) {
    return false;
    }
    if (id.length === 12) {
    // Validate century prefix and reduce string that is to be validated to 10 digits
    // Other prefixes than these indicate that it is a company
    var prefix = parseInt(id.substring(0, 2));
    if (prefix < 18 || prefix > 20) {
    return false;
    }
    // Validate that year is not greater than current
    var currentYear = (new Date()).getFullYear();
    if (parseInt(id.substring(0, 4)) > currentYear) {
    return false;
    }
    id = id.substring(2);
    }
    var sum = 0;
    for (var i = 0; i < id.length; i++) {
    var value = parseInt(id.charAt(i));
    sum += getValidationValue(i, value);
    }
    return sum % 10 == 0;
    }

    function getValidationValue(index, baseValue) {
    if (index % 2 !== 0) {
    return baseValue;
    }
    var doubled = 2 * baseValue;
    if (doubled < 10) {
    return doubled;
    } else {
    return 1 + (doubled - 10);
    }
    }

    var toTest = [
    8209244113,
    "8209244113",
    "820924-4113",
    "820924+4113",
    "18820924-4113",
    "19820924-4113",
    "201302091077",
    " 82 09 24 - 4113",
    null,
    "",
    "8209244119",
    "AA09244113",
    "AA8209244113",
    "820924B4113",
    "17820924-4113",
    "20820924-4113",
    "201202091077",
    " 82 09 24 _ 4014"
    ];

    toTest.forEach(function(value) {
    var ok = isValid(value);
    console.log(value + " is valid: " + (ok ? 'true' : 'false'));
    })