Skip to content

Commit

Permalink
Add date checking to f-numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
pearofducks committed Jul 12, 2019
1 parent 9df0a59 commit 47ebf2c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
24 changes: 24 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,34 @@ function checkType (fodselsnummer) {
return parseInt(fodselsnummer[0], 10) > 3 ? 'D' : 'F'
}

function hasValidDate (fodselsnummer) {
if (parseInt(fodselsnummer[0], 10) > 3) {
return true // skip date check for d-numbers
}
const d = parseInt(fodselsnummer.substr(0, 2))
const m = parseInt(fodselsnummer.substr(2, 2)) - 1
const y = parseInt(fodselsnummer.substr(4, 2))
const currentCentury = 2000
const yyyy = currentCentury + y
const date = new Date(yyyy, m, d)
const now = new Date()
const previousCenturyYYYY = yyyy - 100
if (date > now) return isValidDateValues(previousCenturyYYYY, m, d)
else return isValidDateValues(previousCenturyYYYY, m, d) || isValidDateValues(yyyy, m, d)
}

function isValidDateValues (yyyy, m, d) {
const date = new Date(yyyy, m, d)
return date.getFullYear() === yyyy && date.getMonth() === m && date.getDate() === d
}

module.exports = function (fodselsnummer, type) {
if (fodselsnummer.length !== 11) {
throw new Error('Too short. Expected length of 11.')
}
if (!hasValidDate(fodselsnummer)) {
throw new Error('Invalid date for fodselsnummer.')
}

var day = fodselsnummer.substr(0, 2)
var month = fodselsnummer.substr(2, 2)
Expand Down
16 changes: 12 additions & 4 deletions test/isValidFodselsnummer.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ tap.equal(
)

tap.equal(
false, isValidFodselsnummer('12341234567'),
'12341234567 is not a valid ID-number'
false, isValidFodselsnummer('11111234567'),
'11111234567 is not a valid ID-number'
)

tap.throws(
Expand All @@ -21,6 +21,14 @@ tap.throws(
'Throws if number too short'
)

tap.throws(
function () {
isValidFodselsnummer('30029012311')
},
{ message: 'Invalid date for fodselsnummer.' },
'Throws if number contains invalid date (for f-numbers only)'
)

tap.equal(
true, isValidFodselsnummer('41085801188'),
'41085801188 is a valid ID-number'
Expand All @@ -37,6 +45,6 @@ tap.equal(
)

tap.equal(
false, isValidFodselsnummer('12341234567', true),
'12341234567 is not a valid ID-number'
false, isValidFodselsnummer('11111234567', true),
'11111234567 is not a valid ID-number'
)

0 comments on commit 47ebf2c

Please sign in to comment.